Am I using malloc correctly?

Good afternoon!

I need to use malloc to create a student list system ... To be effective, our professor asked us to use it in the structure, so I created the structure as follows:

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

every time I add a record, that is, when I use malloc ...

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

then I will free him like that.

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

Am I using malloc correctly ??? what is the effect if i release it like this instead of the loop above.

free(array);

Thanks in advance. Your feedback will be highly appreciated.

+3
source share
10 answers

Are you all right.

free(array);will be undefined, because it itself was arraynot allocated through malloc, so you cannot freeand do not need it - the memory will be controlled by the compiler.

+4

:

type *something;
something = malloc(n * sizeof(*something));

, , -, . sizeof - , - .

, void *, malloc, C, .

, :

(struct student*)malloc(sizeof(struct student));

malloc(sizeof(**array));
+3

, malloc, , .

, . .

struct student * next . struct student_list_node, struct student struct student_list_node * next;

:

struct student_list_node
{
  struct student data;
  struct student_list_node * next;
};

struct student_list_node * head;
struct student_list_node * tail;

struct student_list_node * addStudentToTail()
{
   struct student_list_node * newnode = (struct student_list_node *)(malloc( sizeof(struct student_list_node ) );
   /* check malloc did not fail or use a checking vesrion of malloc */
   if( !tail )
   {
      head = tail = newnode;
   }
   else
   {
      tail->next = newnode;
      tail = newnode;
   }
   return newnode; // which is also "tail"
}

int main()
{
   struct student_list_node * node = addStudentToTail();
   struct student * pstud = &node->data;
   /* write to pstud student details */
}

, , *, calloc, malloc

struct student * array = (struct student *)calloc( 30, sizeof( student ) );

free(array) . , realloc. ( : , , realloc ).

+2

. , , . , , .

.

+1

, , .

*array[30] 30 , free() .

+1

, . , , . , 30 ...

, free() , malloc(). , .

. Undefined Behavior, ( ) free(), malloc().

+1

.

( ) 30

 struct student *array = (struct student *)malloc(30*sizeof(struct student));

,

free(array)
+1

. , , malloc , .

malloc , - :

int arraySize = 30;
student * ourArray = (student*)malloc(sizeof(student) * arraySize);

. , , , . , , , .

, .

+1

struct student NULL

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

, [i] NULL

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

: malloc() free() , malloc. , .

+1

Source: https://habr.com/ru/post/1778256/


All Articles