Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a pointer returned by std::string.c_str() or std::string.data() have to be freed?

As far as i know, std::string creates a ident array-copy of its content when you call the c_str()/data() methods (with/out terminating NUL-char, does not matter here). Anyway, does the object also take care of freeing this array or do I have to?

In short:

std::string hello("content");

const char* Ptr = hello.c_str();

// use it....

delete[] Ptr;   //// really ???

I just want to be on the safe side when it comes to memory allocation.

like image 801
BeschBesch Avatar asked Sep 18 '11 09:09

BeschBesch


Video Answer


3 Answers

No you don't need to deallocate the ptr pointer.

ptr points to a non modifyable string located somewhere to an internal location(actually this is implementation detail of the compilers).


Reference:

C++ documentation:

const char* c_str ( ) const;

Get C string equivalent

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

A terminating null character is automatically appended.

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only guaranteed to remain unchanged until the next call to a non-constant member function of the string object.

like image 162
Alok Save Avatar answered Sep 19 '22 17:09

Alok Save


No need, the dtor of the string class will handle the destruction of the string so when 'hello' goes out of scope it is freed.

like image 34
AndersK Avatar answered Sep 19 '22 17:09

AndersK


std::string handles this pointer so don't release it. Moreover, there are two limitations on using this pointer:
1. Don't modify string that is pointed by this pointer, it is read-only.
2. This pointer may become invalid after calling other std::string methods.

like image 31
Mike Avatar answered Sep 20 '22 17:09

Mike