Discuss: Security Enhancements in Visual C++
by Priyali Vibhute, BS 7799 LA
In all this article, you forgot the fact "hello" is a 6 bytes-size string, not 5. Because "hello" includes the '\0' caracter.
Note that the strncpy(buffer, "hello", 5) won't cause an immediat buffer overrun, but as the '\0' is not added to the end of the buffer, anyone reading the buffer will read farther than its size. And if you copy the buffer, hoping that you only need another 5-sized buffer, you will overrun.
The good solution is:
{
#define BUFFER_MAX_CHAR 5
char buffer[BUFFER_MAX_CHAR + 1] ;
buffer[BUFFER_MAX_CHAR] = 0 ;
strncpy(buffer, "hello", BUFFER_MAX_CHAR) ;
}
As we are protected by both the macro BUFFER_MAX_CHAR and the fact that there is an extra zero at the end of buffer, there is no risk of buffer overrun, no matter the size of the string to be copied via strncpy.
Of course, this won't protect from a strcpy...