Reputation: 11317
This feels like a silly question, but I just can't work out a clean solution and can't find a similar question in the mass of other pointer related questions.
I have some dynamically allocated memory of unknown type and want to store a pointer inside it at the start. Dynamic memory returned by malloc should be suitably aligned so I don't think I have to worry about alignment when writing to the start of the allocated block.
This is my code, which works, but I'm representing a pointer as a 64-bit integer and want to do it in a more clean/portable way:
void *my_area = malloc(512);
void *my_pointer = get_my_pointer();
((long long *) my_area)[0] = (long long) my_pointer;
Upvotes: 3
Views: 1657
Reputation: 18348
Define a struct with internal array of 8 bytes. Replace all the long long type references with your custom struct. This way you will not depend on platform-specific size of long long. The struct will be 64 bits on all platforms(you can add #pragma pack if you worry about alignment )
Upvotes: 0
Reputation: 213328
The cast to long long
is just extra baggage. Cast to void *
instead.
void *my_area = malloc(512);
void *my_pointer = get_my_pointer();
((void **) my_area)[0] = my_pointer;
(I assume that this is for some kind of freelist or the like, i.e., you don't need to use the structure at the same time.)
Upvotes: 2
Reputation: 13651
What will be found in my_area[0]
is pointer to something, right ?
Then you can allocate my_area to be of type void **
, which represent a pointer to a pointer containing memory area.
void **my_area = malloc(512 * sizeof(*my_area)); // alloc 512 pointer sized memory blocks
void *my_pointer = get_my_pointer();
my_area[0] = my_pointer;
Upvotes: 1