C: strncpy() and terminating NULL
Posted on 2013-10-03
I have the following: (line numbers inserted for clarity)
1. char buff, another_buff;
2. char something[;
// the buffer SOMETHING contains text read in via fgets()
3. setmem(buff, sizeof(buff), 0);
4. strncpy(buff, something, 11);
5. buff = '\0';
So far so good. I guard against a buffer overrrun per BUFF by setting the terminating NULL.
So, BUFF might contain "ABCDEFGHIJK". (which is 11 characters)
Now right after the above,, we have
6. if (buff == 'E') // error conditon, meaning the data starts in something
7. strncpy(buff, something+1, 11);
// but years ago whoever wrote this did NOT re-set the terminating NULL.
Are we OK here? In other words, will buff still be NULL per setting it in line 5 above?
so that if I do
strcpy(another_buff, buff, 11);
I won't overrun ANOTHER_BUFF since BUFF will still be properly NULL-terminated?