Friday, February 15, 2008
Binary or String?
I know all good programmers have probably heard all this before but since I recently found some code which does some mixing and matching of binary and string functions I figured it was worth touching on. The following functions read NULL bytes and continue to read input until some event for the storage buffer is filled, recv, read, fgets, and many more. As we all know that the end of a character array is marked by a NULL byte.

What am I getting at here? The main reason I'm posting this is because I recently saw some code which reads in data from a file using fgets(). This code then checks for the first character to see if its a comment character ('#'). If it is it ignores that line and reads the next line. However, the code later looks a little something like this:

buff[strlen(buff)-1] = '\0';


If the first character of the line was a NULL byte the strlen() would return 0 as the first char marks the end of the data. This obviously leads to a simple off-by-one issue.

A more correct version of this would look something like this:

size_t len = strlen(buff);

fgets()
...

if(!len)
return ERROR;

else
buff[len - 1] = '\0';


Of course this is just a simple example of some of the dangers of reading in binary data and treating it as a character array.
 
posted by bannedit at Friday, February 15, 2008 | Permalink | 0 comments