本文介绍了如果malloc()在同一位置分配内存,则访问释放的指针可能会导致数据损坏,除非将释放的指针设置为NULL.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于用户(GeorgSchölly116K声望)在其问题中的陈述,出现了此Question陈述.应该真正设置指针吗?释放它们后将其设置为"NULL"?
This Question statement is came in picture due to statement made by user (Georg Schölly 116K Reputation) in his Question Should one really set pointers to `NULL` after freeing them?
那我怎么弄不到数据将如何损坏?
代码
#include<iostream>
int main()
{
int count_1=1, count_2=11, i;
int *p=(int*)malloc(4*sizeof(int));
std::cout<<p<<"\n";
for(i=0;i<=3;i++)
{
*(p+i)=count_1++;
}
for(i=0;i<=3;i++)
{
std::cout<<*(p+i)<<" ";
}
std::cout<<"\n";
free(p);
p=(int*)malloc(6*sizeof(int));
std::cout<<p<<"\n";
for(i=0;i<=5;i++)
{
*(p+i)=count_2++;
}
for(i=0;i<=3;i++)
{
std::cout<<*(p+i)<<" ";
}
}
输出
0xb91a50
1 2 3 4
0xb91a50
11 12 13 14
再次在释放(0xb91a50)后分配相同的内存位置,但是它工作正常,不是吗?
推荐答案
您不要在代码中重用旧指针.在 p =(int *)malloc(6 * sizeof(int));
之后, p
指向一个不错的新分配数组,您可以毫无问题地使用它.Georg引用的数据损坏问题将在类似于以下内容的代码中发生:
You do not reuse the old pointer in your code. After p=(int*)malloc(6*sizeof(int));
, p
point to a nice new allocated array and you can use it without any problem. The data corruption problem quoted by Georg would occur in code similar to that:
int *p=(int*)malloc(4*sizeof(int));
...
free(p);
// use a different pointer but will get same address because of previous free
int *pp=(int*)malloc(6*sizeof(int));
std::cout<<p<<"\n";
for(i=0;i<=5;i++)
{
*(pp+i)=count_2++;
}
p[2] = 23; //erroneouly using the old pointer will corrupt the new array
for(i=0;i<=3;i++)
{
std::cout<<*(pp+i)<<" ";
}
这篇关于如果malloc()在同一位置分配内存,则访问释放的指针可能会导致数据损坏,除非将释放的指针设置为NULL.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!