在文件上写入时的malloc问题 [英] malloc problem when writing on a file
本文介绍了在文件上写入时的malloc问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每当我在文本文件中写入数据时,就会出现垃圾数据……为什么会这样? 这是我的代码...谢谢
A garbage data appears whenever i write the data in the text file... Why is it like that? Here's my code... Thanks
int main(void)
{
unsigned int option = 0;
int i = 0;
}
getch();
while(option != 5){
option = display();
switch(option){
case 5: save();
break;
}
for(i = 0; i < recordCtr; i++){
free(array[i]);}
}
}
save(){
FILE *stream = NULL;
stream = fopen("student.txt", "wt");
printf("\nSaving the student list directory. Wait a moment please...");
int i =0;
for (i=0; i<3; i++){
fprintf(stream, "%5s %30s %5s\n", array[i]->studentID, array[i]->name, array[i]->course);
}
fclose(stream);
}
推荐答案
有一些错误.
- recordCtr总是递增的.如果我选择加2次,则分别填充array [0],array [1]和array [2].但是,当您释放内存时,您将释放到recordCtr值.在这种情况下,您恰巧释放了最多6条学生记录.可能是灾难.
- 切换结束后,您将释放学生记录的内存.如果用户选择退出,则会对save()进行校准,以尝试保存已释放的学生记录.从释放的内存中读取是个坏主意.
什么时候看到垃圾数据.我的意思是根据什么输入?
When do you see garbage data. I mean under what Input?
这篇关于在文件上写入时的malloc问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文