您的位置:首页 > 其它

malloc和free(2)——malloc()申请内存得到指针,指针被改动,用free释放内存报错

2017-12-06 14:55 656 查看
malloc()分配内存,得到的内存指针,中间经过了改动,再调用free释放内存出现问题

Parr1D1 = data;

这一行代码写的很差,首先就是这个地方确实改变了指针Parr1D1,Parr1D1本身的值变化了。delete(或者free)时就会出现无效指针的错误。

至少给数组赋值应该用memcpy或snprintf函数来做。

Parr1D1 = data;
//以下两个cout都注释掉,报错见图一  free(): invalid size: 0x00007ffc98a56080 ***
//只注释掉第一个,报错见图二       卡住不执行下面的语句
//只注释掉第二个,报错见图三       卡住不执行下面的语句
//两个都不注释,报错见图四   double free or corruption (out): 0x00007ffd66a91210 ***
cout<<"data address: "<<data<<endl;
cout<<"Parr1D1 pointer address After(Parr1D1 = data;): "<<Parr1D1<<endl;

free(Parr1D1);


注意下面这句从来没有被执行

cout<<"GoodBye main()"<<endl;

#include <typeinfo>
#include<stdlib.h> //malloc()头文件
#include<iostream>
using namespace std;

//数组指针

int main()
{
cout<<"Hello main()"<<endl;

int len = 10;

//声明时候赋值NULL
double *Parr1D1 = NULL;
cout<<"Parr1D1 pointer address  Before malloc: "<<Parr1D1<<endl;   //Parr1D1的值是一个指针,顺着这个指针可以从内存中找到数据

Parr1D1 = (double*)malloc(len*sizeof(double));//从此指针知道自己所指向的内存的地址
cout<<"Parr1D1 pointer address  After malloc: "<<Parr1D1<<endl;   //Parr1D1的值是一个指针,顺着这个指针可以从内存中找到数据

/////////////////////////////////////////////
double data[len];
cout<<endl<<"data[i]:  ";

//data是数组名字: 只能通过数组名字加下标的方式访问数组
for(int i=0; i<len; i++)
{
data[i] = i;
cout<<data[i]<<"  ";
}
cout<<endl;
/////////////////////////////////////////////

//Parr1D1 = &data;  会报错: a value of type "double (*)[len]" cannot be assigned to an entity of type "double *"
//这两个语句是等效的:  Parr1D1 = &data; 和 Parr1D1 =  (double *)&data;

Parr1D1 = data;
//以下两个cout都注释掉,报错见图一  free(): invalid size: 0x00007ffc98a56080 ***
//只注释掉第一个,报错见图二       卡住不执行下面的语句
//只注释掉第二个,报错见图三       卡住不执行下面的语句
//两个都不注释,报错见图四   double free or corruption (out): 0x00007ffd66a91210 ***
//cout<<"data address: "<<data<<endl;
cout<<"Parr1D1 pointer address After(Parr1D1 = data;): "<<Parr1D1<<endl;

free(Parr1D1);

cout<<"GoodBye main()"<<endl;
return 0;

}


图一





图二



图三



图四





参考: http://blog.csdn.net/xiamo20149/article/details/51964945
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐