文件操作,释放内存出错http://zhidao.baidu.com/question/316031664.html?fr=im100009

[复制链接]
查看11 | 回复3 | 2011-9-5 08:05:43 | 显示全部楼层 |阅读模式
可恶的百度,追问半天了内容还在审核中。第一个程序输入什么都没关系的,就是第二个程序只要有这一行free(s)就会在程序结束时弹出一个全是英文的窗口说是出错了,没有free(s)就没事#defineBUFFER_SIZE10intmain(void){FILE*pInFile=NULL;FILE*pOutFile=NULL;char*infilename=\"D:\\\\我的文档\\\\c.txt\";char*outfilename=\"D:\\\\我的文档\\\\d.txt\";size_tbuffer_size=BUFFER_SIZE;size_tstr_length=0;intstr_count=0;fpos_t*positions=NULL;inti=0;char*buffer=(char*)malloc(buffer_size);if(!(pInFile=fopen(infilename,\"r\"))){printf(\"Erroropening%sforreading.Programterminated.\",infilename);exit(1);}for(;;){fread(if(feof(pInFile))break;if(str_lengthbuffer_size){buffer_size=str_length1;free(buffer);buffer=(char*)malloc(buffer_size);}fread(buffer,str_length,1,pInFile);str_count;}printf(\"\\nThereare%dstringsintheinputfile.\",str_count);rewind(pInFile);positions=(fpos_t*)malloc(str_count*sizeof(fpos_t));for(i=0;istr_count;i){fgetpos(pInFile,positionsi);fread(fread(buffer,str_length,1,pInFile);}if(!(pOutFile=fopen(outfilename,\"w\"))){printf(\"Erroropening%sforreading.Programterminated.\",outfilename);exit(1);}for(i=0;istr_count;i){fsetpos(pInFile,positionsstr_count-i-1);fread(fwrite(fread(buffer,str_length,1,pInFile);fwrite(buffer,str_length,1,pOutFile);}fclose(pInFile);fclose(pOutFile);printf(\"\\nNewfilewritecomplete.\\n\");pOutFile=fopen(outfilename,\"r\");printf(\"\\nThestringsinthenewfileare:\");for(i=0;istr_count;i){fread(fread(buffer,str_length,1,pOutFile);buffer[str_length]=\'\\0\';printf(\"\\n%s\",buffer);}printf(\"\\n\");fclose(pOutFile);free(buffer);free(positions);return0;}这是书里的代码,它的是对的,我完全照着编的,不明白为什么就出错
回复

使用道具 举报

千问 | 2011-9-5 08:05:43 | 显示全部楼层
关键在于内存申请的大小不对,导致内存溢出。free的时候出错。为什么不对呢?看你的这段程序:fread(if(feof(p))break;if(a=A){free(s);s=(char*)malloc(a1);}假设三个字符串的长度分别为61216一点问题都没有但是假设长度为16126会发生什么问题呢?就是经过上面这个循环之后s所分配的长度是12,而正确的应该是最大的16.你的程序错在把最后一个大于10的长度作为s的内存长度。正确的应该是把最大的长度作为s的内存长度。好了这样改就对了用一个maxsize变量记录一下:intmaxsize=A;fread(if(feof(p))break;if(amaxsize){maxsize=a1;free(s);s=(char*)malloc(maxsize);}这样就ok了
回复

使用道具 举报

千问 | 2011-9-5 08:05:43 | 显示全部楼层
懒得看这么多代码。free的时候报错最常见的情况是由于写内存的时候写过界了。因为在malloc的时候库函数把一些内存分配相关的信息记录在返回的这段内存前面紧挨着的地方,而free的时候就要读这个信息。如果你因为什么原因误写了这块内存,到free的时候就报错。所以好好检查一下,你这个s有没有挪过地方,有没有写s的时候向前过界,有没有在写前一个数组的时候向后过界
回复

使用道具 举报

千问 | 2011-9-5 08:05:43 | 显示全部楼层
回去了帮你调试下,现在我有点忙。sorry追问http://zhidao.baidu.com/question/316031664.html错误的图片终于显示了,高手看看,谢谢!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行