我对C语言还很陌生,所以我不知道这里会发生什么.
在应该以面向对象的方式运行的String
struct 的这个实现中,当我得到以下诊断时,set
函数中似乎有一些错误:
Process finished with exit code -1073741819 (0xC0000005)
这是我的.h文件:
#include <string.h>
#include <stdbool.h>
typedef struct String_Struct
{
char* value;
unsigned int length;
void (*set) (struct String_Struct* self, char* value);
bool (*equals) (const struct String_Struct* self, const struct String_Struct* other);
int (*compareTo) (const struct String_Struct* self, const struct String_Struct* other);
void (*concat) (struct String_Struct* self, const struct String_Struct* other);
void (*freeString) (struct String_Struct* self);
} String;
String* newString (char* value);
void set (String* self, char* value);
bool equals (const String* self, const String* other);
int compareTo (const String* self, const String* other);
void concat (String* self, const String* other);
void freeString (String* self);
以下是它的实现:
#include "mystring.h"
#include <stdlib.h>
#include <stdio.h>
void set (String* self, char* value)
{
// Only proceed if self and value exist
if (!self || !value)
{
return;
}
free(self->value);
self->length = strlen(value) + 1;
self->value = (char*) malloc(sizeof(char) * self->length);
strcpy(self->value, value);
}
int compareTo (const String* self, const String* other)
{
if ((!self && other) || (self && !other))
return INT_MIN;
return strcmp(self->value, other->value);
}
bool equals (const String* self, const String* other)
{
if ((!self && other) || (self && !other))
return false;
if (self == other)
return true;
return strcmp(self->value, other->value) == 0;
}
void concat (String* self, const String* other)
{
if (!self || !other)
{
return;
}
char* result = (char*) malloc(sizeof(char) * (strlen(self->value) + strlen(other->value) + 2));
strcpy(result, self->value);
strcat(result, other->value);
self->set(self, result);
}
void freeString (String* self)
{
free(self->value);
free(self);
}
String* newString (char* value)
{
String* str = (String*) malloc(sizeof(String));
str->set = &set;
str->equals = =
str->compareTo = &compareTo;
str->concat = &concat;
str->freeString = &freeString;
str->set(str, value);
return str;
}
这是我的主电源.
#include <stdio.h>
#include "mystring.h"
int main()
{
String* string = newString("Hello");
printf("%s", string->value);
return 0;
}
当我运行这段代码时,我得到了上面提供的错误.但当我在"set"中添加一个不相关的printf语句时,如下所示:
void set (String* self, char* value)
{
// Only proceed if self and value exist
if (!self || !value)
{
return;
}
printf("Debug");
free(self->value);
self->length = strlen(value) + 1;
self->value = (char*) malloc(sizeof(char) * self->length);
strcpy(self->value, value);
}
以下是控制台输出: 调试Hello 进程已完成,退出代码为-1073741819(0xC0000005)
有谁能解释一下原因吗?