I’d like to ask about memory allocation in 64-bit ubuntu Linux.
I have the following code
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buffer_one[8], buffer_two[8];
printf("Size of char: %u\n", sizeof(char));
printf("Buffer_two is at %p\n", buffer_two);
printf("Buffer_one is at %p\n", buffer_one);
}
and when it is run, the following result shows up
$ ./sizeofchar
Size of char: 1
Buffer_two is at 0x7fff98069910
Buffer_one is at 0x7fff98069900
My question is that even with size of char type is 1 byte and I assume (please correct me if I’m wrong here) Buffer_two and Buffer_one are allocated next to each other, why does the Buffer_two and Buffer_one memory address are allocated 16 bytes apart.
This is compiler-dependent behavior. Since these are stack-allocated buffers (which really has nothing to do with memory allocation,) it is up to the compiler how the stack local variables are laid out in the stack. You could play with this, but I would guess that all arrays are allocated on the stack in 16-byte increments, for one reason or another.
If you look at the disassembly, you could see where in the stack frame the variables are set to be. I have a hunch that a
char[2]andchar[15]both end up taking 16 bytes in the stack frame. Why, I’m not exactly sure. But what I can add, is that the x64 ABI specifies that the stack is always 16-byte aligned, and this type of allocation will make it easy to guarantee that.