C中链接列表中的空指针

时间:2015-11-13 05:10:40

标签: c linked-list function-pointers nodes void-pointers

我有一个程序,它有一个向结构返回void *的函数,但我认为在渲染数据时我忽略了一些东西。

此函数创建一个包含字符串和int的结构。字符串是从文件中读入的。

physical_address = PFN * page_size + offset

这是调用它并接受void *。

的函数
void * buildWord(FILE * fin)
{
     void * ptr;

     char buf[100];
     Words * nw = (Words *)calloc(1, sizeof(Words));

     fgets(buf, 100, fin);
     strip(buf);
     nw->word = (char *)calloc(1, (strlen(buf) + 1));
     nw->length = strlen(buf);

     strcpy(nw->word, buf);

     ptr = &nw;

     return ptr;
}

这是Node

的结构
Node * buildNode(FILE * in, void *(*buildData)(FILE * in) )
{
     Node * nn = (Node *)calloc(1, sizeof(Node));

     nn->data = (Words*)((*buildData)(in));
     return nn;
}

我知道单词结构的创建很好,但是当我开始使用列表中的节点时,其中没有数据。我不知道为什么会这样。谢谢!

2 个答案:

答案 0 :(得分:2)

您需要进行一些更改。

  1. git update-ref -d refs/original/refs/heads/master返回的值不对。而不是

    buildData

    你可以使用

    ptr = &nw; // This is the address of nw. It will be
               // a dangling pointer once the function returns.
    
    return ptr;
    

    你可以从函数中删除return nw;

  2. 由于从ptr返回的值是与您使用的指针不同的指针,因此需要更改buildData的返回值的使用。而不是

    buildData

    你需要使用:

    nn->data = (Words*)((*buildData)(in));
    

答案 1 :(得分:1)

你的函数buildword声明了一个变量ptr,它是函数范围的本地变量。当你返回它时,为变量分配的内存被释放,这会引起悬空指针的上升。

而不是使用

ptr = &nw;
return ptr;

DO

return (void*)nw;