【发布时间】:2015-04-14 19:08:08
【问题描述】:
我正在使用以下功能
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() 后我的变量无效?
【问题讨论】:
-
*str 是变成 NULL 还是 str 本身? str 是堆栈或寄存器中指针的副本,即使在某些内存管理问题的情况下,也不应该受到对 malloc 的调用的影响。这同样适用于 pch。
-
如果
header为NULL,header->next = h;将是一个问题。你有多确定header不为NULL? -
@Meixner 在
malloc之前,它包含一个字符串("foo"),但在调用之后它是NULL,所以我会说str本身。 -
@RSahu 当我在 while 循环之前的任何位置设置断点时,
header指向一个有效对象,并且它的name值设置正确。 -
尝试使用除
malloc()之外的任何其他函数调用分配给 h。如果你得到类似的行为(变量任意改变),你就会遭受堆栈损坏。