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 {
/*
....
*/
}
}
A structure is a collection of variables of same or different datatypes. It is useful in storing or using informations or databases. Example: An employee's record must show its salary, position, experience, etc. It all can be stored in one single variable using structures.
Increased productivity: structure in C eliminates lots of burden while dealing with records which contain heterogeneous data items, thereby increasing productivity. Maintainability of code: using structure, we represent complex records by using a single name, which makes code maintainability like a breeze.
C Structures. Structure is a user-defined datatype in C language which allows us to combine data of different types together. Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar type only.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With