malloc problem when writing on a file

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);                     
}

Answers


There are some bugs.

  1. 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.
  2. 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?


Need Your Help

Must-revalidate headers of this request wrong?

apache http apache2 http-headers

I noticed that chrome cached a video file. I replaced it with another one on the server and chrome kept serving the old one from cache (using JW flash player 5)

Node.js cannot find module - interfering with cygwin on Windows

node.js cygwin twitter-bootstrap less npm

I'm testing the Bootstrap framework (from Twitter) and try to build it locally after installing Node.js. It fails because it cannot find the less module (which I have also installed with 'npm insta...