Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Structures in C

Tags:

c

malloc

struct

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 {

    /* 
        ....
    */

    }
}
like image 813
cyan Avatar asked Feb 23 '18 13:02

cyan


People also ask

What are the uses of structures?

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.

What are the advantages of structure in C?

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.

What is structure C and what is its purpose?

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.


1 Answers

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.

like image 164
unwind Avatar answered Oct 19 '22 08:10

unwind