I have some memory and I try to allocate it in several pieces.
So I have a linked list. Each node keeps track of the size the allocated piece of memory is and the next node.
When I return the pointer to the requester, I return a pointer right after this node ends (say return newNode + sizeOf(node)) because the requester needs just the memory to use.
The problem is when I try to free it by changing the node. When myFree is called with a pointer and I do pointer – sizeOf(node) to get to the node, it doesn’t work.
What am I doing wrong?
I don’t think it’s useful but here’s some code:
#define HEADER(24)
printf("Original pointer %-10p\n", pointer);
head *toUse = pointer + HEADER;
printf("Pointer to memory to be used %-10p\n", toUse);
printf("Trying to read the header again %-10p\n", toUse - HEADER);
The first and third printf gives me different addresses. That’s the problem.
As for testing, I just allocate one piece of memory at the beginning and it still doesn’t work.
In C,
(pointer + n)is equivalent to&pointer[n]… that is, the index counts the items the pointer points to, not bytes. If you want a byte offset, use((char*)pointer + n). But in your case you don’t need a byte offset; instead ofyou can just do
or
Although you probably want to cast those to
(void*)if you’re returning a pointer to something that the caller can use as any type. To get back to the original node from the(void*)pointer, use either(node*)vp - 1or(node*)((char*)vp - sizeof(node)).Also,
won’t compile because it resembles a function-like macro; you need at least one space between the macro name and the left parenthesis (or omit the parentheses).