Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am i using malloc properly?

Tags:

c

malloc

Good day!

I need to use malloc in creating a student list system.... In order to be efficient, our professor asked us to use it on a struct so i created a struct as follows:

struct student {
       char studentID[6];
       char name[31];
       char course [6];
};
struct student *array[30];

everytime i add a record, that is when i use malloc...

array[recordCtr]=(struct student*)malloc(sizeof(struct student));
recordCtr++;

then i free it like this.

 for(i = 0; i < recordCtr; i++){
       free(array[i]);
  } 

Am i using malloc properly??? what is the effect if i free it like this instead of the loop above.

free(array);

Thanks in advance. Your opinion will be highly appreciated.

like image 479
newbie Avatar asked Dec 04 '22 10:12

newbie


1 Answers

You are doing fine.

free(array); would be undefined behavior because array itself was not allocated via malloc therefore you can't free it and don't need to - the memory will be managed by the compiler.

like image 107
Armen Tsirunyan Avatar answered Dec 11 '22 09:12

Armen Tsirunyan