Sunday, November 16, 2008

Tips for reducing unexpected buffer errors

When using functions such as strncpy() that take a size input parameter, you should use the size of the destination buffer and not the source buffer for correct functionality!

Following code snippet is an example of incorrect usage -

strncpy(dest, src, sizeof(src));

//If sizeof(src) > sizeof(dest) this would give unexpected results;


Therefore, the correct and safe usage should be,

memset(dest, 0, sizeof(dest)); //Fill the buffer with null characters

strncpy(dest, src, sizeof(dest)-1);

//sizeof(dest)-1 takes care of the space for the terminating null character

0 comments: