OnlyHughman OnlyHughman - 1 month ago 10x
C Question

Struct pointer syntax confusion

Hi i'm relatively new to c and was wondering if anyone could explain what exactly i'm doing with the following code.

I have a struct:

typedef struct free_list_header {
u_int32_t magic; // ought to contain MAGIC_FREE
vsize_t size; // # bytes in this block (including header)
vlink_t next; // memory[] index of next free block
vlink_t prev; // memory[] index of previous free block
} free_header_t;

and I'm initialising it within a function using the following...

void vlad_init(u_int32_t size)

int sizePow2 = pow(2, ceil(log(size)/log(2)));
memory = malloc(sizePow2*sizeof(char));
memory_size = sizePow2;
strategy = BEST_FIT;

free_header_t *freeHeader = (free_header_t*)memory;

freeHeader->magic = MAGIC_FREE; // the unique value
freeHeader->size = memory_size; // amount we malloc'd
freeHeader->next = 0; // position of next free block
freeHeader->prev = 0; // position of prev free block
free_list_ptr = 0;

my question is what exactly am i doing here and why is it necessary?

free_header_t *freeHeader = (free_header_t*)memory;

So... i'm declaring a new struct by pointing to it named "freeHeader"? and that is a pointer to it in the memory i have allocated? So this is a way of putting the struct into the malloc'd area to access it out of the function in which im initializing it?


Malloc returns a void pointer (type void*). This means it returns a pointer to a memory address and that pointer is not pointing to any specific type. So after the line:

memory = malloc(sizePow2*sizeof(char)); //sizePow2 is n bytes to allocate

memory is a pointer of type (void *).

free_header_t *freeHeader = (free_header_t*)memory;

On the left hand side here you are creating a pointer named freeHeader that points to a memory address containing something of type free_header_t Since you explicitly said this pointer is pointing to an address of type free_header_t to you are casting the other side (currently of type void *) to match it as free_header_t *.

NOTE in C, this works but is not necessary. The compiler will automatically cast a void * to whatever type you need. However writing code like this is good practice, in C++ you need to explicitly do this.