Search code examples
c++pointersdereferencestrdup

Dereferencing pointer to char pointer c++


I have the following code:

char **ptr;
*ptr=strdup("This is a pointer");
cout<<*ptr<<endl;

When I try to execute it I get segfault at the cout instruction. If I do instead

char *ptr;
ptr=strdup("This is a pointer");
cout<<ptr<<endl;

Everything works correctly. What causes the problem and what is the workararound? I am not looking for solutions of the type "Use strings".


Solution

  • char **ptr; //I have a pointer to pointer to char
    *ptr = ...; //I dereference the pointer I never initialized and, wait...
    

    ptr was never initialized to point to anything. When you dereference and assign to it, you're getting undefined behavior. Either just don't use ** pointers when you don't need them, or initialize ptr.

    char** ptr = new char*(strdup("where did my rubber duck go"));