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]);}
}
开发者_如何学Go}
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);
}
There are some bugs.
- recordCtr is always incremented. If I chose to add 2 times then you fill array[0], array[1] and array[2]. But when you are freeing memory, you are freeing up to recordCtr value. In this case you happen to free up to 6 student records. It could be disaster.
- As soon as the switch ends you are freeing student records memory. If user choose to exit then save() is caled which tries to save student records which are freed already. Its bad idea to read from freed memory.
When do you see garbage data. I mean under what Input?
You never allocate memory for struct student *array[MAX];
I think this is overwriting your data maybe?
strcpy(array[0]->studentID, dummy);
studentID is a char[5] and dummy is a char[30]. It's been a while since using C for m, but you could be smashing your other data.
精彩评论