问题出在主题名称中。如何使用已知地址分配内存?在c ++中,我们可以使用operator new(std::size_t, void* p)
的展示位置形式。如何在纯c
中完成?
答案 0 :(得分:7)
C ++的 placement-new 运算符在给定地址(而不是内存本身)中分配对象,并调用其构造函数。
如何使用已知地址分配内存?
那不是内存分配。您已经分配了内存(并且知道有效位置的地址),或者根本没有(因此您没有地址,或者地址不是有效< / 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;
答案 1 :(得分:1)
在C中已知地址使用内存的正确方法如下:
struct s { unsigned a; }; /* structure presumed to exist at some known location */
unsigned int loc = 0x100; /* address in known memory */
struct s* ploc = (struct s*)loc; /* cast to any pointer - see below */
s->a = 0; /* zap it */
见n1570 S6.3.2.3 / 7
整数可以转换为任何指针类型。除非事先指明,否则 结果是实现定义的,可能没有正确对齐,可能不指向 引用类型的实体,可能是陷阱表示。
无需分配。只是使用它。但不要弄错。
答案 2 :(得分:0)
#include <stdio.h>
int main(void) {
int buffer[3] = {0};
int *address;
printf("Address of middle element is %p.\n", (void*)(buffer + 1));
printf("Enter address to assign to (try the value above +/- %d): ", (int)sizeof (int));
fflush(stdout);
scanf("%p", (void**)&address);
*address = 42;
printf("buffer contents: %d, %d, %d.\n", buffer[0], buffer[1], buffer[2]);
return 0;
}