什么是释放指针和分配为NULL之间的区别? [英] What is the difference between freeing the pointer and assigning it to NULL?

查看:117
本文介绍了什么是释放指针和分配为NULL之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我之间的区别:

  INT * P;
P =(INT *)malloc的(10 * sizeof的(INT));
自由(对);

  INT * P;
P =(INT *)malloc的(10 * sizeof的(INT));
p值= NULL;


解决方案

免费将释放的内存 P 点 - 只需将其分配给 NULL 不会(因此你将有一个内存泄漏)

值得一提的是,这是很好的做法来分配你的指针 NULL 调用免费之后,因为这将prevent您意外地尝试访问释放的内存(这还是有可能的,但是绝对不应该做的)。

Could somebody tell me the difference between:

int *p;
p=(int*)malloc(10*sizeof(int));
free(p);

or

int *p;
p=(int*)malloc(10*sizeof(int));
p=NULL;

解决方案

free will deallocate the memory that p points to - simply assigning it to NULL will not (and thus you will have a memory leak).

It is worth mentioning that it is good practice to assign your pointer to NULL AFTER the call to free, as this will prevent you from accidentally trying to access the freed memory (which is still possible, but absolutely should not be done).

这篇关于什么是释放指针和分配为NULL之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆