ryantata
ryantata

Reputation: 137

C memory allocation initialising and handling

Having trouble with my task here. I need to create a global block of free memory and malloc it. Having some trouble initialising it due to typecast and handling errors.

Like arrays in C where the first array is actually a pointer to the first element, my memory block needs to be similar where i can use pointer arithmetic to locate blocks of memory.

//global variable
static byte *memory = NULL;

void allocator_init(u_int32_t size){

     *memory = (byte*) malloc(size);
}

The addresses/pointers to these memory addresses will be stored via structs/links as headers of the memory block.

typedef struct _header {
    int signiture;
    int size;
    header* next;
    header* prev;
} header;

Upvotes: 0

Views: 155

Answers (4)

Neil
Neil

Reputation: 485

In your header struct, since the struct references itself, declare the internal header pointers as "struct _header * name;". I think other people have hit all the other points :)

Upvotes: 0

rashok
rashok

Reputation: 13464

*memory = (byte*) malloc(size); - This statement means you are trying to assign the address of the heap memory block as a value to *memory. Here memory is having NULL, so it will crash.

You have to assign the addres to the variable like, memory = (byte*) malloc(size);

Upvotes: 1

user529758
user529758

Reputation:

You need to assign the return value of malloc to the pointer itself, not to the byte pointed to by the pointer. (Anyway, if you dereference the initially NULL pointer, your program will segfault.)

memory = malloc(size);

Also, don't caat the return value of malloc.

Upvotes: 1

cnicutar
cnicutar

Reputation: 182664

Drop the *:

*memory = (byte*) malloc(size);
^

You might also want to drop the cast but that's your call.

Upvotes: 5

Related Questions