Using Structures in C

I am reading a script about implementing malloc (first-fit), and I'm a little confused about assigning values ​​to a metadata structure. Can someone give an explanation why malloc returns flag_block->ptr (as a pointer to allocated memory)? As far as I can see, there is no specific task for him.

 typedef struct _metadata { size_t size; char free; struct _metadata* next; struct _metadata* prev; char ptr[]; } metadata; metadata* flag_block = NULL; void *malloc(size_t size) { if (size==0) { return NULL; } if (flag_block == NULL) { flag_block = sbrk(size); sbrk(sizeof(metadata)); if (flag_block == (void *)-1) { return NULL; } flag_block->free = 0; flag_block->next=NULL; flag_block->prev=NULL; flag_block->size = size; return flag_block->ptr; } else { /* .... */ } } 
+7
c struct malloc
source share
1 answer

ptr is called the flexible element of the array; it is an array without size and can only appear at the end of a struct .

So basically this:

 return flag_block->ptr; 

equivalently

 return &flag_block->ptr[0]; 

So, it returns the address of the first byte after the remaining members in the struct .

+6
source share

All Articles