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:

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 01: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 12:03 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

terryh

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today