Store pointer address in malloced memory

和自甴很熟 提交于 2021-01-27 12:30:37

问题


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;

回答1:


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.)




回答2:


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;



回答3:


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 )



来源:https://stackoverflow.com/questions/13274583/store-pointer-address-in-malloced-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!