The contents of the memory are undefined for str1 because you did not initialize it.
After you copy "HelloWorld" and then nul terminate, then the memory after that is still undefined, ie. probably garbage. You do realize that local variables live in the user stack... and that uninitialized varables lead to bad things like buffer overflows?
One way of several to improve the code.
Also, notice I used code tags so it is easy to read:
memset initializes str1, and main() ALWAYS returns an integer. This is very important in UNIX. Because it was initialized, str1 does need the '\0' tacked on the end. Unless you strncpy something else in there.
as an user of existing libs, i dont think so programmer gets down to the stack to prevent any crash... an actual workout with memory maps and its components
Like I said, there is always the potential for garbage whenever you overwrite a string of unknown contents. Should you fill all string buffers with nulls, every time you overwrite them? That could be an awful lot of nulls.
memset and strncpy are the only standard C string "copy" functions that don't null-terminate the destination string.
And Corona's example of
str[0]='\0';
doesn't handle strncpy, it allows buffer overrun, because there is no trailing '\0'
except by luck of what happened to be in the memory allocated on the stack for str1...
Covers all situations. If strncpy has enough space, it will leave a null terminator at or before the index n, and putting the terminator at the end will do nothing. If it does not have enough space, then by definition it will need one at index n.
This is my understanding of strncpy. As long as it copies n + m characters into the destination from a source that is n bytes long, you're okay.
n-1 and it does not null-terminate.
That's exactly my point, Jim. If you're copying a string into a buffer that's too small, it won't be null terminated. If you're copying a string that's smaller than the buffer, it will be null-terminated.
So, just put a null on the end of the buffer, and it will always be null terminated no matter what the size of the input string.
As usual, there's no need to nullify the whole buffer. For small buffers you can get away with it, but it's not good to get into the habit of it.