I was trying to find out the addresses and sizes of variables in my program using nm, and I just realized a whole bunch of my variables are unexpectedly large. I made a following test file, "test.c":
static char test1 = 0;
static char test2 = 0;
char test_f(void)
{
test1 = test2;
return test2;
}
int main(void)
{
return test_f();
}
Then I run the following commands:
gcc test.c
nm -C -S --size-sort a.exe | findstr /rc:"test"
And the output is
0000000140007040 0000000000000001 b test1
0000000140007041 000000000000000f b test2
0000000140001540 000000000000001a T test_f
I assume some sort of padding / alignment is at play here, but I don't understand why the padding became part of a symbol. Is there a way to produce a similar text log in which test1 and test2 would both have the size of 1?
The
nmman page says “The size is computed as the difference between the value of the symbol and the value of the symbol with the next higher value.” Therefore, if there is padding after variable A and before variable B, the padding will appear as part of the size of A.In your example,
test1was apparently immediately followed bytest2, so the size oftest1was computed as one byte.test2was not followed by any explicit symbol in its program section; the next “symbol” thatnmused may have been the beginning of the next section or the first symbol in it. That next section has some alignment requirement, so there is unused space, also called padding, aftertest2and before the next section. So the difference betweentest2and the next “symbol” includes that padding, and it shows up in the “size” oftest2as the man page states.