c - Setting the first two bytes of a block of memory as a pointer or NULL while still accessing the rest of the block -
suppose have block of memory such:
void *block = malloc(sizeof(void *) + size);
how set pointer beginning of block while still being able access rest of reserved space? reason, not want assign 'block' pointer or null.
how set first 2 bytes of block null or have point somewhere?
this doesn't make sense unless you're running on 16-bit machine.
based on way you're calling malloc()
, you're planning have first n bytes pointer else (where n may 2, 4, or 8 depending on whether you're running on 16-, 32-, or 64-bit architecture). want do?
if is, can create use pointer-to-a-pointer approach (recognizing can't use void* change anything, don't want confuse matters introducing real type):
void** ptr = block;
however, far more elegant define block struct (this may contain syntax errors; haven't run through compiler):
typedef struct { void* ptr; /* replace void* whatever pointer type */ char[1] data; } my_struct; my_struct* block = malloc(sizeof(my_struct) + additional); block->ptr = /* */
Comments
Post a Comment