我正在使用以下功能
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));
之后,变量pch
和str
由于某种原因转向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()
后,为什么我的变量无效?
答案 0 :(得分:0)
如果您需要保留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
以释放内存
答案 1 :(得分:0)