cpointerssegmentation-faultstrtokaddressof

Difference between passing “pointer to pointer” and “address of pointer” to a function


I have a function that takes a char **; it uses it internally for maintaining context between successive calls.

What is the difference between defining char **x and passing x to it, and defining char *x and passing &x?


For context: I tried to implement the example at strtok man page on my own before reading the source code. And I got segfaults. Then after attempts I looked at the source.

The problem was that I defined char **x and passed x as the **saveptr argument, but changing the definition to char *x and the passing to &x solved the problem.

What is the problem exactly?


Solution

  • The first version, with char **x; and passing x, creates and uses an uninitialised pointer to pointer to char.
    The second version, with char * x; and passing &x, creates an uninitialised pointer to char, but passes a value which is a valid address of a pointer to char, and is a defined value (i.e. like an initialised pointer to uninitialised pointer to char).

    Basically with first version you ask to write at a "random" place in memory (almost sure way to get a segfault); with second, you ask to write into an existing pointer variable.