Web Log

Weblog

All | Cycling | Gadgets | General | Installers | Licensing and Registration | Music | Programming | Science and Nature
« Computer-aided music | Main | The Truth Machine »
20050920 Tuesday September 20, 2005

Stupid errors I have made, #1 of several thousand

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:

( Sep 20 2005, 07:08:29 PM PDT ) Permalink Comments [2]
Trackback URL: http://blogs.sun.com/terryh/entry/stupid_errors_i_have_made
Comments:

You may also want to have a look at

  • ftw(3c), and
  • nftw(3c).

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 #

Post a Comment:

Name:
E-Mail:
URL:

Your Comment:

HTML Syntax: NOT allowed

Calendar

RSS Feeds

Search

Links

Navigation

Referers