LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   C seg fault (http://www.linuxquestions.org/questions/programming-9/c-seg-fault-237594/)

drigz 10-01-2004 02:36 PM

C seg fault
 
This code segfaults on the first strtok:
Code:

int mkdirp(char* file)
{
        printf("%s\n", file);
        char* pch;
        pch = strtok(file,"/");
        while (pch != NULL)
        {
                printf("%s\n", pch);
                mkdir(pch, 0777);
                pch = strtok(NULL, "/");
        }
        return 0;
}

I have tried calling it with file = "newdir" and file = "mydir/subdir" - neither work.

itsme86 10-01-2004 02:51 PM

You can't use strtok() on string constants according to the man page:
Code:

BUGS
      Never use these functions. If you do, note that:

              These functions modify their first argument.

              These functions cannot be used on constant strings.

So if main() looks like:
Code:

int main(void)
{
  mkdirp("newdir");
  return 0;
}

...it will crash. But this should work:
Code:

int main(void)
{
  char dirname[] = "newdir";

  mkdirp(dirname);
  return 0;
}


drigz 10-01-2004 03:47 PM

still fails - this is now the relevant part of my main:
Code:

        char* newdir="newdir";
        mkdirp(newdir);
        printf("made newdir\n");
        char* mydir="mydir/subdir";
        mkdirp(mydir);
        printf("made mydir/subdir\n");
        char* newdir2="newdir2/subdir";
        mkdirp(newdir2);
        printf("made newdir2/subdir\n");

since it said i shouldnt use it, is there an alternative to using this (other than making the behaviour myself)?

itsme86 10-01-2004 04:06 PM

This:
Code:

char* newdir="newdir";
...is not the same as...
Code:

char dirname[] = "newdir";
...like I suggested.

It's still segfaulting for you because you're still using a string constant. Use my suggestion and it will work fine.

drigz 10-01-2004 04:14 PM

really? oh well - i just gave up and wrote it myself (turns out i forgot something and it was easier to write it myself)

thanks.

itsme86 10-01-2004 04:35 PM

Yeah, string constants such as "newdir" go into read-only memory. So when you do char *name = "newdir"; you're just creating a pointer that points to read-only memory, but when you do char name[] = "newdir"; you're creating an array and copying the contents of "newdir" into the array. The memory for the array is not in read-only memory.


All times are GMT -5. The time now is 12:36 AM.