gpt4 book ai didi

c - malloc 清空其他变量

转载 作者:太空宇宙 更新时间:2023-11-04 04:37:18 24 4
gpt4 key购买 nike

我正在使用以下功能

int parse_headers(char *str, struct net_header *header)
{
char *pch;
struct net_header *h, *temp;

pch = strtok(str, "\n");
header->name = pch;

h = malloc(sizeof(struct net_header));
header->next = h;
while ((pch = strtok(NULL, "\n")) != NULL)
{
h->name = pch;

temp = malloc(sizeof(struct net_header));
h->next = temp;
h = temp;
}
return N_SUCCESS;
}

直到 header->next = h 行,一切都按计划进行。但是,在 h = malloc(sizeof(struct net_header)); 行之后,变量 pchstr 出于某种原因变成了 NULL (我设置断点来找到这个)。在 temp = malloc(sizeof(struct net_header)); 行之后,header 也变为 NULL。显然,我有某种内存管理问题,但我似乎无法找到它是什么。 header 参数在我调用函数之前立即像这样初始化

header = malloc(sizeof(struct net_header));

struct net_header 声明为

struct net_header
{
char *name;
char *content;
struct net_header *next;
};

我运行了 Xcode 的静态分析器,没有发现任何问题。我也没有编译器警告或错误。我在 Mac OS X 10.9 上运行这个程序。

为什么在我调用 malloc() 后我的变量被取消了?

最佳答案

如果你需要保留 strtok 结果,你必须复制它,例如 strdup

int parse_headers(char *str, struct net_header *header)
{
char *pch;
struct net_header *h, *temp;

pch = strtok(str, "\n");
header->name = strdup(pch);

h = malloc(sizeof(struct net_header));
header->next = h;
while ((pch = strtok(NULL, "\n")) != NULL)
{
h->name = strdup(pch);

temp = malloc(sizeof(struct net_header));
h->next = temp;
h = temp;
}
return N_SUCCESS;
}

你需要在某处调用free来释放内存

关于c - malloc 清空其他变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635488/

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