有关内存回收的问题
学C++学得有点空中楼阁了,一些比较基本的知识不小心给扔掉了
以下是我写的一个测试代码,作用是将结构体abc中的全部数据写入文本文档123中,然后再从123中进行读取
#include <iostream>
#include <fstream>
using namespace std ;
typedef struct a
{
int x ;
unsigned char* tt ;
}abc ;
int main()
{
ofstream fout("123.txt", ios::binary) ;
abc* temp = new abc ;
temp->tt = new unsigned char[500] ;
temp->x = 50 ;
int i ;
for(i = 0 ; i < 499 ; i++)
{
temp->tt[i] = 'a' ;
}
temp->tt[i] = '\0' ;
fout.write((char*)temp, sizeof(unsigned char) * 500 + sizeof(int)) ;
fout.close() ;
fout.clear() ;
temp->x = 100 ;//////////// 把这块内存改个值
delete[] temp->tt ;
temp->tt = NULL ;
delete temp ;
temp = NULL ;
ifstream fin("123.txt", ios::binary) ;
temp = new abc ;
temp->tt = new unsigned char[500] ;
fin.read((char*)temp, sizeof(unsigned char) * 500 + sizeof(int)) ;
fin.close() ;
fin.clear() ;
cout<<temp->x<<endl ;/////////// 显示一下这个值
delete[] temp->tt ;
temp->tt = NULL ;
delete temp ;
temp = NULL ;
return 0 ;
}
//////////////// 写入
fout.write((char*)&temp->x, sizeof(int)) ;
fout.write((char*)temp->tt, sizeof(unsigned char) * 500) ;
//////////////// 读取
fin.read((char*)&temp->x, sizeof(int)) ;
fin.read((char*)temp->tt, sizeof(unsigned char) * 500) ;