Search code examples
carraysstringmemory-managementdynamic-memory-allocation

How can puts() find the end of an array without a \0 terminator?


In this code:

int length = atoi(argv[1]);
char *tab = malloc(length * sizeof(char));
memset(tab, '-', length);
puts(tab);

no matter what value I passing to argv[1], the output is correct. For example, for argv[1] = "5" i get ----- (five hyphens).

I'm wondering how puts() can find the end of input string when I have not put a '\0' at the end of my array of chars.


Solution

  • What @aschepler said. I am guessing that something — either the operating system or your C runtime or startup code — is zeroing out the memory before you malloc it. As a result, your string is null-terminated by virtue of the fact that you didn't overwrite the \0 bytes that were already there. Don't assume this will always work!

    Edit Different compilers, OSes, and libraries initialize memory differently. This question and its answers, and likewise this one, give some examples of initialization patterns and other patterns written to memory to assist debugging. Turns out at least one compiler (IBM XLC) lets you choose the value for uninitialized automatics.