I want to ask about a memory allocation question about char *buffer; buffer = malloc(5); and char buffer[5].
My code for test is below:]
#include <stdio.h>
void echo1();
void echo2();
int main() {
echo1();
printf("\n");
echo2();
printf("Back to Main \n");
return 0;
}
void echo1() {
int i;
unsigned long addr;
char *buffer;
printf("[Echo1] Buffer : %p \n", buffer);
printf("[Echo1] &Buffer : %p \n", &buffer);
buffer = malloc(5);
printf("[Echo1] &Buffer : %p \n", &buffer);
printf("[Echo1] Buffer : %p \n", buffer);
for (i = 0; i < 5; i++) {
buffer[i] = 'A';
}
printf("[Echo1] Buffer[] : %s \n", buffer);
addr = &buffer;
printf("[Echo1] *Buffer : %p \n", *buffer);
printf("[Echo1] addr : %p \n", addr);
printf("[Echo1] &addr : %p \n", &addr);
}
void echo2() {
int i;
unsigned long addr;
char buffer[5];
printf("[Echo2] Buffer : %p \n", buffer);
printf("[Echo2] &Buffer : %p \n", &buffer);
for (i = 0; i < 5; i++) {
buffer[i] = 'A';
}
printf("[Echo2] Buffer[] : %s \n", buffer);
addr = &buffer;
printf("[Echo2] *Buffer : %p \n", *buffer);
printf("[Echo2] addr : %p \n", addr);
printf("[Echo2] &addr : %p \n", &addr);
}
I compiled it on ubuntu by typing gcc test.c -o test -m32 (I'm using a 64 machine). And the following figure shows the result.

I think I understand the echo1() case (except for why addr is above buffer), and made a figure to show what happened in the memory.

But I have no idea what happened in echo2() case.
So I want to ask the following questions:
- In echo1(), I declared addr before buffer, why addr is placed above buffer in stack? (since stack moves upward, shouldn't the program firstly push addr and then push buffer above it?)
- In echo2(), why buffer and &buffer give the same value? Doesn't this mean buffer is pointing to itself?
- In echo2(), addr's address and addr's content(address of buffer) is separated by 12 bytes, what is stored in them?
- Can anyone make a figure to help me understanding what happened in ehco2()?
Thanks a lot.
%s, the argument must be a null-terminated string. You never added a null byte to thebuffer. - Barmar