Article 6NEJK CodeSOD: Terminated Nulls

CodeSOD: Terminated Nulls

by
Remy Porter
from The Daily WTF on (#6NEJK)

When you get into the world of proprietary filesystems, things can get real weird. There are many a filesystem that doesn't support directories, still in use today. Or filesystems which only allocated chunks in multi-megabyte blocks, which means you end up wasting a lot of space if you have small files. Or filesystems where the largest file size is itself a handful of megabytes.

Dan was working on one such filesystem where, when you opened a file for writing, you could specify how many "fixed records" it needed to support. So, for example, if you wanted to open a file for writing, in binary mode, you might do this: open(pathToFile, "f4096wb"): support 4096 records, and open it for writing.

Now, Dan's predecessor wanted to do exactly that: open a file for writing, with 4096 records.

This was their C code for doing that:

char str[256];strcpy (str, "f4096");strcat (str, (char *) "w");strcat (str, "b\0");strcat (str, "\0");

This code creates an empty array of characters 256 characters long. Then it copies the string "f4096" in. Then we use strcat to concatenate "w"- which we cast as (char*) which... fine? I suspect they originally tried to use 'w'- a character, not a string- and got confused when it didn't work. And then struggled when (char*)'w' segfaulted. And by the time they landed on (char*)"w" they'd forgotten why they put the (char*) in there to begin with.

Then they concatenate "b\0"- a "b" followed by a null terminator (which, also, the string literal also ends with a null terminator, not that it matters, as strcat stops at the first one). Then, for good measure, we concatenate another null terminator.

All this could have been done with a simple string literal. None of this code is necessary. It certainly makes things more confusing to anyone reading the code.

This block of code should be taken to be representative of the project that Dan was working on. This kind of "logic" was strewn all about the code.

proget-icon.png [Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments