使用指针到指针的重新分配行为

Realloc behaviour using a pointer-to-pointer

我不明白为什么当我 运行 这段代码时,printf 语句不起作用。 这是代码:

typedef struct list {
    int n;
    struct list *next;
}List;

List **head;


List *tmp=malloc(sizeof(List));
tmp->n=34;
tmp->next=NULL;
List *tmp2=malloc(sizeof(List));
tmp2->n=45;
tmp2->next=NULL;
List *tmp3=malloc(sizeof(List));
tmp3->n=26;
tmp3->next=NULL;


head=malloc(sizeof(head));
head[0]=tmp;
head[1]=tmp2;
head=realloc(head,sizeof(head));
head[2]=tmp3;
printf("n of tmp:%d \n",head[0][0].n);
printf("n of tmp2:%d \n",head[1][0].n);
printf("n of tmp3:%d \n",head[2][0].n);

我认为这可能是 realloc 的原因,但为什么呢?我使用得当,不是吗?我已按照本教程进行操作 http://www.tutorialspoint.com/c_standard_library/c_function_realloc.htm

不仅realloc,这里

head = malloc(sizeof(head));

你只为一个指针分配space,然后

head[0]=tmp;
head[1]=tmp2;

您尝试存储 2。

如果你需要space 2个指针,那么正确的方法是

head = malloc(2 * sizeof(*head));
    /*                   ^ always dereference when using sizeof */
    /* in this case it's not a problem, but in other cases it will be */

然后你可以填充两个元素,在检查malloc()的return值之后所以

head = malloc(2 * sizeof(*head));
if (head == NULL)
    doSomething_But_DontDereference_head_mayBe_exit();
head[0] = tmp;
head[0] = tmp2;

现在,realloc(),如果 realloc() returns NULL,你已经覆盖了 head 指针,现在你不能做其他任何东西,所以

void *pointer;

pointer = realloc(head, 3 * sizeof(*head));
if (pointer == NULL)
    doSomethingAndProbablyFree_head_and_abort();
head = pointer;

安全多了。

另外,请注意,您需要将指针的大小 sizeof(*head) 乘以您要存储的指针的数量。

始终检查 malloc()

的结果

您的代码相对损坏。这是解决此问题的一种相当明智的方法:

typedef struct list {
    int n;
    struct list *next;
} List;

int main() {
    List *tmp1 = malloc(sizeof(List));
    tmp1->n = 34;
    tmp1->next = NULL;

    List *tmp2 = malloc(sizeof(List));
    tmp2->n = 45;
    tmp2->next = NULL;

    List *tmp3 = malloc(sizeof(List));
    tmp3->n = 26;
    tmp3->next = NULL;

    List **head = malloc(2 * sizeof(List *));
    head[0] = tmp1;
    head[1] = tmp2;
    head = realloc(head, 3 * sizeof(List *));
    head[2] = tmp3;

    printf("n of tmp1: %d\n", head[0]->n);
    printf("n of tmp2: %d\n", head[1]->n);
    printf("n of tmp3: %d\n", head[2]->n);
}

我没有包括这个,但你也应该验证 malloc()realloc() return 是一个非空指针。