How to determine the memory structure of a structure?
Suppose I have the following structure (in C):
struct my_struct {
int foo;
float bar;
char *baz;
};
If now I have a variable say
struct my_struct a_struct;
How can I find out how the fields of this structure will be laid out in memory? In other words, I need to know what the address will be a_struct.foo
, a_struct.bar
and a_struct.baz
. And I cannot do it programmatically because I am actually cross-compiling to a different platform.
EXPLANATION
Thanks to the answers so far, but I cannot do it programmatically (i.e. with a macro offsetof
or with a small test program) because I am doing cross-compilation and I need to know how the fields will be aligned on the target platform. I know this is implementation dependent and the whole point of my question. I am using GCC for compilation targeting ARM architecture.
Eventually I will need to flush memory from the target platform and parse it with other tools like the Python library struct
. But for this I need to know how the fields were laid out.
source to share
In general, this is a specific implementation. It depends on things like compiler, compiler settings, platform you are compiling, word size, etc. Here is a previous SO thread on the topic: C struct memory layout?
If you are doing cross-compilation, I would assume that the specific layout will differ depending on which platform you are compiling on. I would suggest links for your compiler and platform.
source to share
One hacky way to see the memory representation of what's inside that would be to draw a pointer to a char pointer and then print all the characters, like this:
struct my_struct s;
s.foo = MAX_INT;
s.bar = 1.0;
s.baz = "hello";
for (int i = 0; i < sizeof(s); i++) {
char *c = ((char*)&s) + i;
printf("byte %d: 0x%02x\n", i, *c);
}
This does not clearly show the boundaries, you would have to infer that from the dump.
Comments made by others about packaging still apply; you will also want to use explicit sized types such as uint32
instead ofunsigned int
source to share
I think you have two options.
The first is to use it __attribute__((packed))
after the structure is declared. This ensures that each member is allocated exactly the amount of memory that its type requires.
Another is to look at your structure and use the alignment rules (n-byte base type variable must be n-byte-aligned) to figure out the layout.
In your example, in each case, each member variable will occupy 4 bytes and the structure will occupy 12 bytes in memory.
source to share