Home > Software design >  How do I view metadata in the first 4 bytes of a void*?
How do I view metadata in the first 4 bytes of a void*?

Time:11-19

So I have void *ptr and I want to view the first 4 bytes, which is some integer.

Initially I thought I should do:

void *return_val = *(int *)ptr;

Is this right? I know how to move my pointer using sizeof after I view the metadata but I am not 100% sure on how to assign that integer in the metadata to a variable.

CodePudding user response:

If ptr did not originally point to an int object then attempting to reinterpret the bytes in this manner is a strict aliasing violation.

The proper way to do this would be to use memcpy to copy the bytes into an int:

int val;
memcpy(&val, ptr, sizeof val);
  • Related