程序中指向一个声明的变量的指针是否可以通过free来释放内存?

int i;

int *p;

p= &i;

free(p);

逻辑上,当然是不行的。

做个简单的例子:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    int *p;
    i = 3;
    p= &i;
    printf("%d\n", *p);
    free(p);

    return 0;
}

这个代码在CS50运行时会提示错误:

*** Error in `./test': free(): invalid pointer: 0x00007ffc3c8f5cf8 ***
Aborted (core dumped)

在codepad上运行也会直接告知:

Segmentation fault

但是,在devc++中运行时,似乎一切正常。正常输出结果3,但是要注意的是:

Process exited after 3.665 seconds with return value 3221226356

main函数返回值不是0,就表明出错了!!!

You have no rights to post comments