以下将要说明一下指针存在栈空间还是堆空间的话题:
废话少说,直接上代码
#include <stdio.h>
#include <stdlib.h>
char *sc_malloc(int size)
{
char *p = (char*)malloc(sizeof(char)*size);
return p;
}
void sc_free(char *p)
{
if(p)
{
free(p);
printf("[%s]\n", p);
printf("[%p]\n\n", p);
p = NULL;
printf("[%s]\n", p);
printf("[%p]\n", p);
}
}
int main(int argc, char const *argv[])
{
char *p = sc_malloc(100);
sc_free(p);
if (p == NULL)
{
printf("free sucess\n");
}
printf("[%s]\n", p);
printf("[%p]\n", p);
return 0;
}
上述代码的执行结果是什么呢?
预想是这样的
[root@6b4ce1faff56 sc_cunit_test]# ./test
[]
[0x2191010]
free sucess
[(null)]
[(nil)]
[]
[(null)]
事实上
可是事实不是这样的,以下是真正运行的结果
[root@6b4ce1faff56 sc_cunit_test]# ./test
[]
[0x2191010]
[(null)]
[(nil)]
[]
[0x2191010]
思考
为什么在调用 sc_free 释放并且将指针 p 置空在之后,在main函数中,打印p的内容为空,地址不为空呢????
事实是这样子的:
p指针的位置是存储在栈空间的,而指针p指向的空间是在堆上的,调用 free 函数,只能释放掉堆空间的指针,在调用sc_free() 函数,即是在函数内部将p置为NULL,但是对栈空间的变量操作,做为返回值是不生效的。所以导致了,在main函数中调用 sc_free 之后,发现判断p == NULL ,不成功。
所以在调用sc_free之后,尽量手动将 p 置空,而不是在 sc_free 内部置空。