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]
You may also want to have a look at
instead of re-implementing tree walk.
Alan.
Posted by Alan Hargreaves on September 20, 2005 at 08:05 PM PDT #
Thanks Alan! Actually that wasn't the particular wheel I was re-inventing in this case, but ftw(3c) should certainly be used for walking existing directory structures.
Posted by Terry Heatlie on September 21, 2005 at 07:03 AM PDT #