MandleBro
Excuse the interruption, but how DO you know the size of a struct without sizeof?
You can get the size creating an array of the struct, and subtracting the pointer positions of two adjacent elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 | #include <stdio.h>
typedef struct foo
{
int x;
int y;
void *handle;
} foo;
main()
{
int From, To, SizeOfFoo;
foo Foo[2] = {0};
From = (intptr_t)(&Foo[1].x);
To = (intptr_t)(&Foo[0].x);
SizeOfFoo = From - To;
printf("Size of Foo: %d\n", SizeOfFoo);
}
/*
sizeof(x) = 4
sizeof(y) = 4
sizeof(handle) = 8
Calc Size = 16
Actual Size = 16
*/
|
The reason this works is due to specification of C, where it states that an array is a contiguously allocated set of objects. I would link you to the standard...but apparently it's not free? And the ones I did find online I'm not quite sure if any modifications were done. Plus, you would need to know the version of C or C++ that you are using.
The thing is, if it was not guaranteed, then a lot of pointer arithmetic would not be possible...
The other reason it works is that the first element of a struct is positioned at the location of the struct. In C at least, there is no extra metadata that a struct contains.
| | Name | Value |
|-----------|--------------------|
| &Foo[0] | 0x00000000002dfe80 |
|-----------|--------------------|
| &Foo[0].x | 0x00000000002dfe80 |
|-----------|--------------------|
|
However, it should be noted that if the compiler puts in padding due to align the members better, it will also include that size (pointer alignment is mentioned in Casey's intro to C stream, I believe).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 | #include <stdio.h>
typedef struct bar
{
int x;
int y;
void *handle;
char filler[12];
} bar;
main()
{
int From, To, SizeOfBar;
bar Bar[2] = {0};
From = (intptr_t)(&Bar[1].x);
To = (intptr_t)(&Bar[0].x);
SizeOfBar = From - To;
printf("Size of Bar: %d\n", SizeOfBar);
}
/*
sizeof(x) = 4
sizeof(y) = 4
sizeof(handle) = 8
sizeof(filler) = 12
Calc Size = 28
Actual Size = 32
*/
|