If you do other things before that call, your stack area will contain other data than an unused one. Imagine that:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int use_stack(void) {
char str[500];
memset(str, 'X', sizeof(str));
printf("Filled memory from %p to %p.\n", &str, &str + sizeof str);
}
void print_stuff() {
int i;
char str[16]; // Changed that so that 10..15 contain X
for(i = 0; i < 10; i++) {
str[i] = (char)(i+97);
}
printf("%s<END>", str); // Have a line break before <END>? Then it comes from i.
printf("&str: %p\n", &str);
printf("&i: %p\n", &i);
// Here you see that i follows str as &i is &str + 16 (0x10 in hex)
}
int main() {
use_stack();
print_stuff();
}
your stack area will be full of X
es, and printf()
will see them.
In your situation and your environment, the stack is coincidentally "clean" on program start.
This may or may not happen. If the compiler puts the variable i
immediately after the array, your data will nevertheless be NUL
-terminated, because the first byte is the value of i
(which you happen to print as well—it might be a libne break in your case—and the second byte is a NUL
byte. Even if this is the case, your code invokes UB (undefined behaviour).
Can you have a look (by piping the program output into hexdump
or alike) if your output contains a 0A
character? If so, my guess is correct. I just tested it, and on my compiler (GCC) it seems to be the way.
As said, nothing you should rely on.
If you see a line break before <END>
, my guess was right. And if you have a look at the pointers now being printed, you can compare their addresses in memory.