I am wondering how does printf() figure out when to stop printing a string, even I haven\'t put a termination character at the end of the string? I did an experiment by mall
It isn't just luck that unterminated strings tend not to cause problems on small programs.
On most OSs/processors malloc rounds up allocations to multiples of 4 or 8 bytes (dependent on the memory alignment requirements of the processor) so there are often (but not always) a few spare bytes at the end of the string.
Typically when malloc requires more memory it is allocated one or more virtual pages (typically 4k) by the OS. For security reasons the pages have to be wiped if they were last used by a different process (or have not been used since warm reset?).
Therefore, because there are lots of zeros about (both in the allocated area and just following) there is a good chance that non-terminated strings will not cause a problem at startup or in small, short running programs (which ironically includes most test programs) but will show up later on when malloc reuses freed blocks.
To guard against this class of problem, development and test builds should use something like efence with the EF_FILL option to set the malloc'd memory to a non-zero value.
Similarly it is a useful idea to initialise the stack to non-zero values as - on most machines with VM - the stack is built from 4k pages that are wiped before being allocated to a process.
Note that even using things like efence there is still a problem with static variables - the whole area is wiped to zero as the program is loaded (and again data is aligned) so an unterminated string will probably go unnoticed if a static string variable is written to only once - the problem will only be noticed if a string variable is re-used to store a shorter unterminated string.
On a related issue, the alignment of variables explains why not allocating enough room for the terminating NUL of a string often goes undetected.