0

In my code here I am trying to return the first part of a string using strtok. But when I do it returns nonsense e.g. 0���. In my case I would want it to return "hi".

char * headPathName(char *path) {
    char pathcpy[strlen(path) + 1];
    strcpy(pathcpy, path);
    char *filename = strtok(pathcpy, "/");
    return filename;
}

int main(void) {
    char *str = "hi/hello";
    char *name = headPathName(str);
    printf("%s\n", name);
}

If I add a print statement printf("%s\n", filename); inside the headPathName function before it returns I get the error:

enter image description here

I do not know why this is happening any help would be great thanks.

Jin
  • 23
  • 5
  • 1
    `pathcpy` is a local variable. Local variables are only valid within the function. Returning and using references to a local variable outside its valid scope is undefined behaviour. – kaylum Oct 28 '21 at 02:02
  • Well I dont want strtok messing with my original string, would I have to create a new char pointer for pathcpy? – Jin Oct 28 '21 at 02:13
  • 2
    Did you read the duplicate post? There are multiple answers in there already. – kaylum Oct 28 '21 at 02:14
  • 1
    @jin, you can copy `path` into `pathcpy`, but if you're going to do this, `pathcpy` needs to be dynamically allocated if you want a pointer to it to be meaningful outside of `headPathName`. – Chris Oct 28 '21 at 02:15
  • Okay so ived change pathcpy to be dynamically allocated (i.e char* pathcpy), does this mean I would have to free the return value in my main? – Jin Oct 28 '21 at 02:21
  • 1
    yes. need to free. – kaylum Oct 28 '21 at 02:23
  • alr thanks everybody for the help! – Jin Oct 28 '21 at 02:24

0 Answers0