Pointer Problem

I have a memory location stored on my heap. I need to extract that memory location and store that as a pointer. Here is what I have done:

1
2
3
4
5
6
char *bp = first_free //global pointer

while (bp != heap_listp) { //heap_listp is a pointer to the start of the heap
  //do some stuff
  bp = (char *)(*(bp + 4)); //the next value of bp is stored 4 bytes away
}


This compiles, but returns a value of 0x0 to bp, rather than the location stored 4 away. (this is a little weird - I've stripped out the extraneous stuff)

Anyone know how to extract an address stored at a memory location and convert that back into a pointer?

Thanks.
1
2
3
4
5
char c = 'a'; //a single character allocated on the stack
char *p = &c; //Pointer to a char
char **p2p = &p; //Pointer to a (Pointer to a char), essentially points to a variable that holds a memory address
unsigned long v = unsigned long(p); //assuming sizeof(unsigned long) == sizeof(char*)
//p2p points to the variable holding a memory address, and v has the integer value that represents that memory address 
Other than this, I have no idea what you want or how to help you.
1
2
3
4
5
// this
bp = (char *)(*(bp + 4));

// is the same as this
bp = (char *)(bp[4]);


So basically you're taking the 5th character, then casting that character to a pointer, which is nonsense.

This is a key example of why you should not cast around compiler errors. If what you are doing makes sense, then you usually should be able to do it without casting. If the only way to shut the compiler up is to cast it, then it's a sign that you're probably doing something wrong.

In this case, if you want to increase the pointer so it points to 4 chars after where it does now, then all you have to do is increase it:

 
bp += 4;


That's it.


EDIT

I just realized I misunderstood what you were asking. Whoops!

Anyone know how to extract an address stored at a memory location and convert that back into a pointer?


The question I have to ask is why would an address be stored in a char*? Shouldn't it be a char**?

At any rate, what you are trying to do is this:

1
2
char** bp2 = reinterpret_cast<char**>(bp);
bp = bp2[1];


Or if you want to condense it to a one liner:

1
2
3
4
bp = (reinterpret_cast<char**>(bp))[1];

// or...
bp = *(reinterpret_cast<char**>(bp + 4)); // caution! 


Note that the 2nd form assumes sizeof(char*) == 4, which may not always be the case.
Last edited on
The question I have to ask is why would an address be stored in a char*?


That's what pointers store. Addresses. A char* holds the address of a char :)
No I mean his char* holds the address of a pointer =P
Topic archived. No new replies allowed.