Tuesday September 20, 2005
Today's stupid programming error involves recursive directory handing in C. I was doing this, and wondering why it didn't work:
void
foo(char *path)
{
/* stuff */
if(condition) {
foo(dirname(path));
/* other stuff */
}
/* yet more stuff */
}
Can you see the problem? Yup, that's right, dirname() modifies the string pointed at by its argument, so when you pop up a level, your path is still trimmed. The solution is to strdup(path) before the recursive call, and free() the copy afterwards.
D'oh!
Tag: Bugs
( Sep 20 2005, 07:08:29 PM PDT ) Permalink Comments [2]