free的简单问题
当两个指针同时执行同一块内存,释放这块内存的方式是什么?
int *p1 = (imt *)malloc(10);
int *p2;
p2 = p1;
1、free(p1);p1 = NULL;free(p2);p2 = NULL;
2、free(p1);p1 = NULL;p2 = NULL;
3、free(p2);p2 = NULL;p1 = NULL;
请各位思考后回答下,并说明理由!
[解决办法]
2.3都可以,p1,p2指向同一块内存区域,只能释放一次
[解决办法]
ISO/IEC 9989:1999 7.20.3.2 The free function
.
.
.
2 The free function causes the space pointed to by ptr to be deallocated, that is, made
available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if
the argument does not match a pointer earlier returned by a memory management
function, or if the space has been deallocated by a call to free or realloc, the
behavior is undefined.
对同一个指针多次free,其行为是未定义的。
2,3都可以。
[解决办法]
p1 p2 都指向的是同一个地址 ,只需要释放他们中任意一个就行了 ,2,3都行
[解决办法]
自己注意好不要重复释放
[解决办法]
这就是使用指针最麻烦的地方,多个指针指向同一个地方...
[解决办法]