Reputation: 101
I am reading the script on the implementation of malloc
(first-fit), and I am a little confused about the value assignment of metadata structure. Could anyone give some explanations why the malloc
returns flag_block->ptr
(as a pointer to the allocated memory)? As far as I can see, there is no specific assignment to it.
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 {
/*
....
*/
}
}
Upvotes: 7
Views: 122
Reputation: 399703
The ptr
is called a flexible array member; it's an array without a size, and can only appear at the end of a struct
.
So basically this:
return flag_block->ptr;
is equivalent to
return &flag_block->ptr[0];
So it's returning the address of the first byte after the rest of the members in the struct
.
Upvotes: 6