C ++ char array out of scope or not?

I have a method that requires a const char pointer as input (not null terminated). This is a requirement of the library (TinyXML) that I am using in my project. I am getting input for this method from calling the string.c_str () method.

Do I need to delete this char pointer? The line is out of scope immediately after the call ends; so the line should remove it using a destructor call, right?

+1


a source to share


4 answers


The char array returned by string.c_str () is nul complete. If the tinyXML function accepts a non-null terminated char * buffer, then you are likely to get some unexpected behavior.

const char * c_str () const;

Get the C string equivalent

Generates a zero character sequence (c-string) with the same content as a string object and returns it as a pointer to an array of characters.

The trailing null character is automatically added.

No, it doesn't need to be released. String destructor does this for you.



The returned array points to an internal location with the required space to store this character sequence plus its null-character termination, but the values ​​in this array must not be modified in programs and are only provided unchanged until the next call to the non-constant member function String object.

source: http://www.cplusplus.com/reference/string/string/c_str/

+8


a source


Don't remove memory from std :: string :: c_str. The string is responsible for this (and it is entirely possible that it gave you a pointer to its internal buffer, so if you delete it it will be bad (tm)).



+10


a source


On another note,
If you don't need the char pointer to be null, then you are better off using str.data()

rather than str.c_str()

. The difference is that it .data()

doesn't provide that what you get will be null terminated. This is useful if your string just takes up the entire length of the internal buffer allocated string

. In this case, the call .c_str()

will force the string

reallocation of the date to a new larger buffer, the ones that contain enough space to add '\0'

at the end.

In any case, of course, you shouldn't delete the returned pointer. string

will take care of this.

+4


a source


std :: string.c_str () returns a pointer to a null terminated string. The actual character array still belongs to the std :: string object and is valid as long as:

  • Std :: string object is valid and
  • No calls to non-const member functions on the std :: string object are made (i.e. changing the string invalidates any previous C-style string it points to).

Up to the very string object to allocate and deallocate nul terminated array-of-char, it is returned to you.

You can always use a nul-terminated string as a non-nul-terminated string. After all, NTS is just non-NTS with an extra zero at the end. As long as the string is properly terminated, as the function expects, it will never see the "extra" null. :)

+1


a source







All Articles