Is there a dangling pointer problem in this code?

166 Views Asked by At
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?

3

There are 3 best solutions below

2
Irad Ohayon On BEST ANSWER

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.

1
MikeCAT On

Assuming that the type of str is std::string, neither of the code is are correct.

char *a=str.c_str();

is invalid because c_str() will return const char* and removing const without casting (usually const_cast) is invalid.

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

is invalid because str.length() don't count the terminating null-character while allocating for terminating null-character is required to use strcpy().

There are no dangling pointer problem in code posted here because no pointers are invalidated here.

0
Stephen M. Webb On

Possibly.

Consider this.

char const* get_string() {
    string str{"Hello"};    
    return str.c_str();
}

That function returns a pointer to the internal value of str, which goes out of scope when the function returns. You have a dangling pointer. Undefined behaviour. Watch out for time-travelling nasal monkeys.

Now consider this.

char const* get_string() {
    string str{"Hello"};
    char const* a = new char[str.length()+1];
    strcpy(a, str.c_str());
    return a;
}

That function returns a valid pointer to a valid null-terminated C-style string. No dangling pointer. If you forget to delete[] it you will have a memory leak, but that's not what you asked about.

The difference is one of object lifetime. Be aware of scope.