Andy Rivera
Andy Rivera

Reputation: 33

Accessing a struct given an unknown pointer to a memory address - C

Suppose I am given a (void*) ptr (my basic understanding is, it represents a pointer to a region of unknown data type) passed through the parameter of a function. I am trying to figure out how to access and check if a struct exists a few addresses behind.

To clarify, I am working with a big char array (not malloced) and the ptr passed into the function should point to an address of an unspecified data type within the array. Located before this data is a struct for which I am trying to access.

void function(void *ptr)
{
       void *structPtr = (void*)((void*)ptr - sizeof(struct block));
}

Would this work to get me a pointer to the address of the struct located behind the initial "ptr"? And if so, how could I check if it is the block struct?

Apologizes in advance, I know this code is not specific as I am fairly new to the concepts entirely but also, I am in the process of coming up with an algorithm and not yet implementing it. Any references to possibly useful information are much appreciated.

Upvotes: 0

Views: 239

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126203

The usual way of writing this is something like:

...function(void *ptr) {
    struct block *hdr = (struct block *)ptr - 1;

relying on pointer arithmetic automatically scaling by the size of the pointed at type. As long as all the pointers passed in here were originally created by taking a pointer to a valid struct block and adding 1 to it (to get the memory after it), you should be fine.

Upvotes: 0

OznOg
OznOg

Reputation: 4722

what you are trying to do is risky as you must be sure that you address a correct place in memory. Usually, we add some magic number in struct block so that we can test here that we are not going anywhere.

This pattern is generally used in memory allocators, have a look to https://sourceware.org/glibc/wiki/MallocInternals for an example.

Upvotes: 1

Related Questions