BeschBesch
BeschBesch

Reputation: 393

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 an identical array-copy of its content when you call the c_str()/data() methods (with or without the terminating NUL-char; it 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.

Upvotes: 7

Views: 4565

Answers (5)

Mike
Mike

Reputation: 1727

std::string handles this pointer, so don't release it. Moreover, there are two limitations on using this pointer:

  1. Don't modify the string that is pointed by this pointer; it is read-only.
  2. This pointer may become invalid after calling other std::string methods.

Upvotes: 4

Xion
Xion

Reputation: 22770

Not only don't you need to free the pointer, but you in fact should not. Otherwise, the destructor of std::string will attempt to free it again which may result in various errors depending on the platform.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206526

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

ptr points to a nonmodifiable string located somewhere to an internal location (actually, this is an 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.

Upvotes: 8

AndersK
AndersK

Reputation: 36082

There isn't any need. The destructor of the string class will handle the destruction of the string, so when 'hello' goes out of scope, it is freed.

Upvotes: 2

Desmond Hume
Desmond Hume

Reputation: 8607

The std::string class is responsible for freeing the memory allocated to contain the characters of the string when an object of the class is destructed. So if you do

delete[] Ptr;

before or after hello object is destructed (leaves the C++ {} scope it was created in), your program will run into a problem of trying to free a memory block that is already freed.

Upvotes: 0

Related Questions