Suppose i write,
char **p;
p[0] = strdup("hello");
Strdup creates a duplicate string in heap with ending character '\0'; As p is pointer to pointer of char, p[0] = strdup("hello") seems perfectly fine for me. But why am i getting segmentation fault.
Let's look at a simpler example. Suppose you say
ipis a pointer to one or moreints -- but it's not initialized, so it points nowhere, soip[0]isn't a valid memory location, so we can't store the value 5 there.In the same way, when you said
pis a pointer that points nowhere. If it did point somewhere, it would point to another pointer. But it doesn't point anywhere, soblows up.
To fix this, you need to make
ppoint somewhere, and specifically to memory allocated to hold one or more pointers. There are many ways to do this:or instead of using a pointer, use an array to start with:
After any of those,
p[0] = strdup("hello")should work.For way 3, we would also need to check that
mallocsucceeded (that it dd not return a null pointer).For ways 2 through 4, we could also set
p[1]throughp[9]. But for way 1, onlyp[0]is valid.See also this answer to a different question for more discussion about trying to use uninitialized pointers.