我对 C 还很陌生,所以我不知道这里会发生什么。
在应该以面向对象的方式运行的“String”结构的实现中,“set”函数似乎存在一些错误: 进程完成,退出代码 -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;
}
这是我的 main.c:
#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)
谁能解释一下为什么?
至少
set
功能有问题:
free(self->value);
self->length = strlen(value) + 1; // you dereference self
// that has just been freed
取消引用已释放的指针没有意义,并且物联网会导致未定义的行为(大多数情况下会导致某种崩溃)。
如果删除
free(self->value);
,您的代码似乎可以工作。我没有进一步调查,因此这段代码中的其他地方可能存在更多问题。