0
点赞
收藏
分享

微信扫一扫

【C++】【VScode】控制台闪退,静态空间分配造成内存不足

墨香子儿 2022-01-27 阅读 57

使用链表读取文件(.csv 大小1663kb),控制台闪退,空间不足。
原因:char BookName[1000];等,绝大部分字符串都不会超过1000字节,直接静态字符串浪费空间。

class Book						//存储图书信息的类
{
public:
	char BookName[1000];			    //书名,用于查找	
	char Writer[1000];			    //作者名,用于查找
	char PublishDate[20];		//出版日期,用于查找
	char ISBN[30];				//ISBN 号,用于查找
	char ebook[2];				//电子书 
	char paperbook[2];			//纸质书  
	char Publisher[1000];		    //出版商,用于查找
	char BriefIntroduction[1000];    //该书内容简介
	int i_o;					//判断书是否借出,0 为在架,1 为借出
	Book *next;					//指向下一个节点的指针
};

改为,字符指针,动态分配空间

class Book						//存储图书信息的类
{
public:
	char *BookName;			    //书名,用于查找	
	char *Writer;			    //作者名,用于查找
	char PublishDate[20];		//出版日期,用于查找
	char ISBN[30];				//ISBN 号,用于查找
	char ebook[2];				//电子书 
	char paperbook[2];			//纸质书  
	char *Publisher;		    //出版商,用于查找
	char *BriefIntroduction;    //该书内容简介
	int i_o;					//判断书是否借出,0 为在架,1 为借出
	Book *next;					//指向下一个节点的指针
};

static void save_file()					//存储文件
	{
		Book *p;           //临时节点
	    fstream file;
		string s1,s2,s3,s4,s5,s6,s7,s8,s9;
		char a1[1000];
		file.open("library//big.csv",ios::in | ios::out);
		if(!file)
		{
			cout<<"[save_file] big.csv not open file"<<endl;
			return;
		}
		getline(file,s1,',');
		head_ptr->BookName=new char[strlen(s1.c_str())+1];
		strcpy(head_ptr->BookName,s1.c_str());
		getline(file,s2,',');
		head_ptr->Writer=new char[strlen(s2.c_str())+1];
		strcpy(head_ptr->Writer,s2.c_str());
		getline(file,s3,',');
		strcpy(head_ptr->PublishDate,&s3[0]);
		getline(file,s4,',');
		strcpy(head_ptr->ISBN,&s4[0]);
		getline(file,s5,',');
		strcpy(head_ptr->ebook,&s5[0]);
		getline(file,s6,',');
		strcpy(head_ptr->paperbook,&s6[0]);
		getline(file,s7,',');
		head_ptr->Publisher=new char[strlen(s7.c_str())+1];
		strcpy(head_ptr->Publisher,s7.c_str());
		getline(file,s8);
		head_ptr->BriefIntroduction=new char[strlen(s8.c_str())+1];
		strcpy(head_ptr->BriefIntroduction,s8.c_str());
		node = head_ptr;
		while(!file.eof())
		{
			p = new Book[sizeof(Book)];
			getline(file,s1,',');
			if(s1=="")//增强鲁棒性,如果文件被换行,最后一行为空,不加的话会最后一个节点错误
			{
				break;
			}
			p->BookName=new char[strlen(s1.c_str())+1];
			strcpy(p->BookName,s1.c_str());
			getline(file,s2,',');
			p->Writer=new char[strlen(s2.c_str())+1];
			strcpy(p->Writer,&s2[0]);
			getline(file,s3,',');
			strcpy(p->PublishDate,&s3[0]);
			getline(file,s4,',');
			strcpy(p->ISBN,&s4[0]);
			getline(file,s5,',');
			strcpy(p->ebook,&s5[0]);
			getline(file,s6,',');
			strcpy(p->paperbook,&s6[0]);
			getline(file,s7,',');
			p->Publisher=new char[strlen(s7.c_str())+1];
			strcpy(p->Publisher,&s7[0]);
			getline(file,s8,'\n');
			p->BriefIntroduction=new char[strlen(s8.c_str())+1];
			strcpy(p->BriefIntroduction,&s8[0]);
			p->next=NULL;
			node -> next= p; 
			node = p;
			// j++;
			n++;//书的数量
			//  cout<<"书的数量: "<<n<<endl;
		}
		file.close();
		delete p;
	}

总结:大量数据存储,每一个结构体分配的长度不相同,使用定长char浪费内存,使用动态空间的分配节约内存。

举报

相关推荐

0 条评论