Dienstag, 26. Februar 2008

memccpy considered harmful ( if you don't know how to use it)

Ever heard of the memccpy function?

It is very similar to memcpy, but it will stop copying if given delimiter character is encountered. So that's a nice feature - let's just use it instead of memcpy everywhere!

Except that you must pay extreme attention to what are you actually copying, and what kind of delimiter character are you using. Copying text strings and using line feed '\n' as delimiter is fine, but copying mac addresses, and using '\n' as delimiter, as a coworker did, is not.
But why, you may ask. Well because the '\n' character, 0x0a in hex, is pretty valid byte to come in a mac address. And guess what - if you use memccpy to copy a mac address and use '\n' as delimiter, it is going the get truncated! And because the target buffer is already allocated with certain size and filled with some random data, that may also be valid for mac address, this kind of error may go unnoticed for a long time.

This brings up the question of the data representation, that you are using and how well you understand it, and also the quality of the interface definitions of common C functions and stuff like:

if(strcmp(str1, str2)) {
/*
if you are expecting to get here
if str1 and str2 are the same,
you are in for a surprise
*/
}


Otherwise remember it also very important to always check the return values, that you are getting and event more important also: test, test, test

Keine Kommentare: