I wrote the following expecting to get a seg fault or garbage output by printf
#include <stdio.h>
#include <stdlib.h>
main(){
char* test = malloc(1);
*test = 'a';
*(test+1) = 'b';
*(test+2) = 'c';
*(test+3) = 'd';
*(test+4) = 'e';
*(test+5) = 'f';
printf("%s\n", test);
}
Instead the output was:
abcdef
I only allocated 1 byte, so why am I allowed to write passed that single byte? Also, how does printf know when the string is terminated? Are all of the bytes that I don't explicitly assign characters to the null-character? I would expect these to be random garbage, yet it seems to terminate at the right spot. I hope this is specific enough! Thanks.