Search code examples
c++pointersc-str

Is there a dangling pointer problem in this code?


string str;    
char *a=str.c_str();

This code is working fine for me but every place else I see this code instead

string str;
char *a=new char[str.length()];
strcpy(a,str.c_str());

I wonder which one is correct and why?


Solution

  • The two code segments do different things.

    The first assigns the pointer value of str to your new c-tpye string, and implicitly converts from const char*(c_str() return type) to char*, which is wrong. If you were to change your new string you would face an error. Even if c_str() returned char*, altering the new string would also make changes in str.

    The second on the other hand creates a new c-type string from the original string, copying it byte-by-byte to the new memory allocated for your new string. Although the line of code you wrote is incorrect, as it does not cover the terminating null character of a c-type string \0. In order to fix that, allocate 1 extra byte for it:

    char *a=new char[str.length()+1];
    

    After copying the data from the first string to your new one, making alterations to it will not result in changes in the original str.