pws5068
pws5068

Reputation: 2194

Question on Pointer Arithmetic

Heyy Everybody! I am trying to create a memory management system, so that a user can call myMalloc, a method I created. I have a linked list keeping track of my free memory. My problem is when I am attempting to find the end of a free bit in my linked list. I am attempting to add the size of the memory free in that section (which is in the linked list) to the pointer to the front of the free space, like this.

void *tailEnd = previousPlace->head_ptr + ((previousPlace->size+1)*(sizeof(int));

I was hoping that this would give me a pointer to the end of that segment. However, I keep getting the warning:

"pointer of type 'void*' used in arithmetic"

Is there a better way of doing this? Thanks!

Upvotes: 0

Views: 475

Answers (2)

SDReyes
SDReyes

Reputation: 9954

int *tailEnd = ( int* ) ( previousPlace->head_ptr + ((previousPlace->size+1)*(sizeof(int)) );

Upvotes: 1

Michael
Michael

Reputation: 55435

Pointer arithmetic uses the size of the underlying type. If int is 4 bytes:

int *p = some_address;
p++; 

will increment p by 4 bytes. void can't be used in pointer arithmetic because void has no size associated with. If you want to do byte-sized arithmetic on void pointers, you need to cast the pointers to a byte-sized type.

Upvotes: 5

Related Questions