Freeing up variable dimensional structure in C

I use a variable size C structure as shown below:

typedef struct {  
  int num_elems;  
  int elem1;  
} mystruct;  
// say I have 5 elements I would like to hold.  
mystruct * ms = malloc(sizeof(mystruct) + (5-1) * sizeof(int));  
ms->num_elems = 5;  
// ... assign 5 elems and use struct  
free(ms);

Will it be the last free () free all that was malloc'd, or just sizeof (mystruct)?

+3
source share
2 answers

Yes. This will free the entire block that was allocated with malloc.

If you allocate one block of memory with malloc(as in your example), you need to call freeexactly once to free this whole block.

+4
source

, , , , , , malloc malloc.

, , malloc'd, , , , SIGSEV SIGBUS, , .

, , , , , .

+2

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


All Articles