问题在主题名称中。如何使用已知地址分配内存?在 C++ 中,我们可以使用运算符 new(std::size_t, void* p) 的放置形式。如何用纯c
完成它?
最佳答案
C++ 的 placement-new 运算符在给定地址(而不是内存本身)内分配对象,并调用其构造函数。
How to allocate a memory using known address?
那么它就不是内存分配了。您要么已经分配了内存(并且您知道有效位置的地址),要么根本没有分配内存(那么您没有该地址,或者该地址无效/em>)。
假设您已经拥有预分配内存块的地址,则您已经可以使用它:
struct MyStruct { int x; };
void* my_address = ...; // known and already allocated chunk of memory, e.g.
// - from stack: char mem[sizeof(MyStruct)]; -> mem
// - from heap: malloc(sizeof(MyStruct));
// - any location that can be considered `valid'
struct MyStruct* my_struct = my_address;
my_struct->x = 1;
关于c - 如何使用纯 C(而不是 C++)中的已知地址分配一 block 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25699680/