malloc使其他变量归零

时间:2015-04-14 19:08:09

标签: c malloc

我正在使用以下功能

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()后,为什么我的变量无效?

2 个答案:

答案 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)

我尝试重现您的错误,在Mac OS X 10.10上运行,并且您的代码没有问题,它运行正常。

您的问题来自于malloc()的另一次调用,其大小不正确,如postthis one,通常是通过传递指针的大小而不是真实的变量大小的类型。

我无法告诉你,因为我没有看到你的整个代码在此之前运行了#34;糟糕的电话",我无法在评论中提问,因为我没有足够的权利。

希望它有所帮助。