Proper memory cleanup with c_str() and const char *

1.4k Views Asked by At

I have a function that takes a (char* const*). The data I am provided is in a std::string. So I'm doing this:

void blahblah(std::string str)
{
   const char * cc = str.c_str();
   ConstCharFunction(&cc);
}

This works well. My question is do I need to clean-up the memory used by the const char ala:

delete cc;

Or is cc just a pointer to a mem location in std:string...

2

There are 2 best solutions below

2
On BEST ANSWER

It's a pointer to memory allocated in std::string. When the std::string falls out of scope, the memory is released. Be sure not to hold onto the pointer after that!

0
On

No you don't need to delete cc. It is indeed a pointer held by the std::string object.

See here

A program shall not alter any of the characters in this sequence.

The pointer returned points to the internal array currently used by the string object to store the characters that conform its value.

Just be careful as the pointer returned by c_str() may be invalidated by calling modifying methods of the string.