结构指针自由导致错误
Struct pointer free causes error
我有以下结构:
typedef struct {
char* type;
char* address;
int area, price;
}Offer;
这两个函数:
Offer* initOffer(char* type, char* address, int area, int price)
{
Offer* p;
p = (Offer*)malloc(sizeof(Offer));
p->type = (char*)malloc(sizeof(type));
p->address = (char*)malloc(sizeof(address));
strcpy(p->type, type);
strcpy(p->address, address);
p->area = area;
p->price = price;
return p;
}
void destroyOffer(Offer* offer)
{
free(offer->type);
free(offer->address);
free(offer);
}
当我调用 destroyOffer 时出现问题,我不知道为什么,但是当我 运行 代码时,我有一个错误提示:检测到堆损坏。如果我删除这两行,它工作正常但我想内存没有正确清理:
free(offer->type);
free(offer->address);
问题:
p->type = (char*)malloc(sizeof(type)); // That's just the size of a pointer
p->address = (char*)malloc(sizeof(address)); // Same problem.
之后,行:
strcpy(p->type, type);
strcpy(p->address, address);
最终覆盖了他们不应该覆盖的内存。这会导致未定义的行为。
你需要:
p->type = malloc(strlen(type)+1);
p->address = malloc(strlen(address)+1);
见Do I cast the result of malloc?
如果您的编译器支持,您也可以使用 strdup
。如果是这样,您的代码可以简化为:
p->type = strdup(type);
p->address = strdup(address);
我有以下结构:
typedef struct {
char* type;
char* address;
int area, price;
}Offer;
这两个函数:
Offer* initOffer(char* type, char* address, int area, int price)
{
Offer* p;
p = (Offer*)malloc(sizeof(Offer));
p->type = (char*)malloc(sizeof(type));
p->address = (char*)malloc(sizeof(address));
strcpy(p->type, type);
strcpy(p->address, address);
p->area = area;
p->price = price;
return p;
}
void destroyOffer(Offer* offer)
{
free(offer->type);
free(offer->address);
free(offer);
}
当我调用 destroyOffer 时出现问题,我不知道为什么,但是当我 运行 代码时,我有一个错误提示:检测到堆损坏。如果我删除这两行,它工作正常但我想内存没有正确清理:
free(offer->type);
free(offer->address);
问题:
p->type = (char*)malloc(sizeof(type)); // That's just the size of a pointer
p->address = (char*)malloc(sizeof(address)); // Same problem.
之后,行:
strcpy(p->type, type);
strcpy(p->address, address);
最终覆盖了他们不应该覆盖的内存。这会导致未定义的行为。
你需要:
p->type = malloc(strlen(type)+1);
p->address = malloc(strlen(address)+1);
见Do I cast the result of malloc?
如果您的编译器支持,您也可以使用 strdup
。如果是这样,您的代码可以简化为:
p->type = strdup(type);
p->address = strdup(address);