gpt4 book ai didi

c - 结构指针释放导致错误

转载 作者:行者123 更新时间:2023-11-30 17:04:25 25 4
gpt4 key购买 nike

我有以下结构:

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);

关于c - 结构指针释放导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35807140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com