I just tried to allocate 10 byte for c string and printed without assigning anything. and I printed over the size of cstring. But result was quite different than I thought. Since malloc only allocates raw memory, I thought it would print any junk values. And since I tried to print over the size of c string, I thought the behavior should be undefined. But they all printed null character I think Here is my code.
int main(void)
{
int i;
char * c = (char *)malloc(10);
for(i=0; i<20; ++i)
{
printf("%c.\n", *(c+i));
}
return 0;
}
And I saw 20 lines of '.' Could anyone explain this? I ran this under Linux, used gcc the latest version Thank you
It hasn't been initialized yet. It needs to be set to a value before you can see anything useful. It simply printed what was already at that memory address (unless a few compiler options are set), which is most likely just 0.