Malloc a struct at a specific point in memory?

2019-09-21 12:48发布

问题:

I'm trying to create a struct at a specific location in memory:

struct inRAM *ptr = (struct inRAM*)malloc(sizeof(struct inRAM));

But this line only allocates the memory at a place in RAM that is not retainable. I need to malloc beginning at a specific memory address for it to work properly, but how?

回答1:

For embedded systems where you need to access specific memory addresses for I/O, you normally write directly to the address.

You don't need to malloc here, that's used to manage blocks of memory or structures where you don't care where it will be located.

e.g. to write to address c00010

ptr = c00010;
ptr->field = value;

Also, when using structures overlayed onto memory be careful about padding and structure alignment.