为什么这个指针操作序列会导致错误?

Ada*_*dam -2 c free pointers

为什么下面的(公认的深奥)指针操作会导致以下错误:

*** Error in /home/ubuntu/workspace/Project 3/Debug/Project 3': double free or corruption (out): 0x00007fffffffd7c0 ***

    int *intPointer = malloc(sizeof(int));
    *intPointer = 1;
    int intArray[] = { *intPointer };
    int *intPointer2 = &intArray[0];
    free(intPointer2);
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 8

分配给的值intPointer2是指向第一个元素的指针intArray.此数组已在堆栈上分配,因此尝试free它是未定义的行为.

您只能free使用malloc/ realloc/ 返回的内存calloc.事实上,此数组中的第一个(也是唯一的)元素包含指向的值intPointer的副本(不是值的副本intPointer)并不重要.

只有打电话free(intPointer)才行.