如何在函数内初始化一个 Struct 指针数组?

How can I initialize an array of Struct pointers inside a function?

我有以下 test.h 文件:

typedef struct node *Node;
struct node {
    const char *key;
    Node next;
};

typedef struct table_s *Table;
struct table_s {
    int n;
    Node *arrayOfNodes;
};

还有这个 test.c 文件:

Table new_table() {
    Table thisTable = malloc(sizeof(Table));
    thisTable->n = 2;
    thisTable->arrayOfNodes = malloc(thisTable->n*sizeof(Node));

    //this line is inserted here so I can check that calling malloc() like this actuallt work
    Node *array = malloc(thisTable->n*sizeof(Node)); 

    return thisTable;
}

int main() {

    Table myTable = new_table();

return 0;
}

程序编译运行,但valgrind.log表示有错误:

==8275== Invalid write of size 8
==8275==    at 0x40056E: new_table (test.c:8)
==8275==    by 0x40043A: main (test.c:18)
==8275==  Address 0x5204048 is 0 bytes after a block of size 8 alloc'd
==8275==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8275==    by 0x40055A: new_table (test.c:6)
==8275==    by 0x40043A: main (test.c:18)

为什么第 11 行的 malloc() 调用工作正常,但第 8 行会导致此错误?这使得我的这个程序的更大版本无法处理大条目(当 n 变大时)。

"Size 8" 是一个线索:它是您系统上指针的大小。你想要分配的是一个对象,而不是一个指针。

sizeof(Node)sizeof(struct node *)一样,sizeof(Table)也有类似的问题

如果你写这样的东西,它会起作用:

typedef struct table_s Table, *TablePtr;
...
TablePtr thisTable = malloc(sizeof(Table));

如果您坚持按原样使用类型,您可以使用以下常见的 malloc 习惯用法:

// General form:
//   T *p = malloc(sizeof *p);
// or:
//   T *p = malloc(N * sizeof *p);
Table this_table = malloc(sizeof *this_table);
...
this_table->arrayOfNodes = malloc(thisTable->n * sizeof *this_table->arrayOfNodes);

Why does the malloc() call in line 11 works fine but in line 8 causes this errors?

因为您分配了一个 Table (size=8),然后尝试访问它就好像它是一个 struct table_s (size=16)。您对 array 的声明很好,但在此之前,您尝试将 malloc 返回的指针写入 this_table->arrayOfNodes,它位于结构中的偏移量 8 处(即偏移量 0 是 n 和偏移量 8 是 arrayOfNodes)。简而言之,您试图在分配的内存之外写入:您只分配了 8 个字节,但您正在写入结构的前 8 个字节。