Max
Max

Reputation: 13

Can't deallocate memory in my C program

I need your help deallocating memory in below program. I tried as you can see in main, but no success. Can not get how to do it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
char name[25];
char street[25];
char citystate[25];
char zip[6];
}student;

 typedef student *studinfo;

 /*function prototypes*/
 void getinfo(student *details[], int *);

 int main(void)
{

int count = 0;
student *studptr[49];

getinfo(studptr, &count);/*call getinfo function to get student info*/


/*int i = 0;
for (i; i<count; i++) {

    free(studptr[i]->name);
    free(studptr[i]->street);
    free(studptr[i]->citystate);
    free(studptr[i]->zip);
   } */

   return 0;
  }

Below is a function to get the info from the file. I will use this info later on in sort function and in display function to display the results. After that I should deallocate the memory.

void getinfo(student *details[], int *count)
{

char s[100];
studinfo info;

/*Get student information*/
while (gets(s) != NULL) {
    info = (studinfo)malloc(sizeof(student));
    strcpy(info->name, s);
    gets(info->street);
    gets(info->citystate);
    gets(info->zip);


    details[(*count)++] = info; /*Increase the pointer to next position*/

    } /* End of while loop*/

     } /* End of getinfo */

Upvotes: 0

Views: 138

Answers (2)

Barmar
Barmar

Reputation: 781058

It should be:

int i;
for (i = 0; i < count; i++) {
    free(studptr[i]);
}

Since you allocated each student as a single block, you free them the same way.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

There are three problems with your code:

  • You are trying to free components of struct student. Since these component arrays were not allocated with malloc, you cannot free them; you need to free only the struct itself.
  • You are using gets, which can cause buffer overruns. You should use fgets instead, passing buffer size, and stdin for the FILE* parameter.
  • You copy s[100] into info->name. This can potentially overrun the buffer, because info->name fits only 25 characters.

Once you fix these issues, your program should run correctly.

Upvotes: 1

Related Questions