按我的理解,
免费()来释放我们之前分配使用malloc内存。
在我下面的代码片段,我释放我已经分配的内存。但我可以释放,即使后访问指针?它是如何可能的?
如何免费内部工作?
#包括LT&;&iostream的GT;使用命名空间std;诠释的main(){ 为int * p =(INT *)malloc的(的sizeof(INT)); * p = 17; 自由(对); * p值= * P + 1; 的printf(\\ n释放内存::%天后,* P); 返回0;}解决方案
您当然可以继续使用 P 呼叫后免费(P)并没有什么会阻止你。然而,结果将完全不确定的和未predictable。它的工作原理只是运气。这就是所谓的在许多节目作品后免费 使用共同的编程错误字面的年没有问题 - 直到它会导致一个问题
有工具,在查找这样的错误,如 Valgrind的。
相当不错As per my understanding,
free() is used to deallocate the memory that we allocated using malloc before.
In my following snippet, I have freed the memory i have allocated. But i was able to access the pointer even after freeing? How it is possible?
How free works internally?
#include<iostream> using namespace std; int main() { int *p=(int *)malloc(sizeof(int)); *p=17; free(p); *p=*p+1; printf("\n After freeing memory :: %d ",*p ); return 0; }解决方案
You can certainly continue to use p after calling free(p) and nothing will stop you. However the results will be completely undefined and unpredictable. It works by luck only. This is a common programming error called "use after free" which works in many programs for literally years without "problems" -- until it causes a problem.
There are tools which are quite good at finding such errors, such as Valgrind.
更多推荐
我们如何能够重新分配存储器后访问指针?
发布评论