我们如何能够重新分配存储器后访问指针?

编程入门 行业动态 更新时间:2024-10-27 07:29:16
本文介绍了我们如何能够重新分配存储器后访问指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

按我的理解,

免费()来释放我们之前分配使用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.

更多推荐

我们如何能够重新分配存储器后访问指针?

本文发布于:2023-07-29 08:41:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239164.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:存储器   指针   分配

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!