Qooraf
Qooraf

Reputation: 1

is memory getting leaked?

i have method which takes normal pointer to string

void parseResponseData(char* response); 

and i am calling this as below

parseResponseData((char *) response.c_str());  

response is std::string type. My assumption is that it may not be the best way for converting const char* to char* and secondly i may be leaking memory in this case? Need expert opinions on that? especially i am looking if am leaking memory on this.

Upvotes: 0

Views: 309

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320381

Your question does not provide enough information to be answered definitively.

Why does parseResponseData require a non-const pointer to its input string? Does it modify the string? If so, then you will not be able to use it with std::string directly. std::string does not provide any interface that would allow you to modify it as a C-style string. Even if you don't care to preserve those modifications, it is still illegal to modify the buffer returned by std::string::c_str().

If parseResponseData does not modify the string, then what you have now should work (assuming parseResponseData does not attempt to store the pointer for long-term use). There's no memory leaks here, since the std::string object retains the ownership of the buffer returned by c_str() and the responsibility to deallocate it. However, it still looks pretty ugly on parseResponseData part: if it is a non-modifying operation, it should take a const char *.

Upvotes: 2

chrisaycock
chrisaycock

Reputation: 37930

Once response goes out of scope, the underlying C string will be freed. The call to parseResponseData() does not make a copy of the C string, only a copy of the pointer. So there is no memory leak.

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

You really should not cast like that. Overall avoid doing c-style cast in c++ and also removing const-ness is almost never a good option. If you have to remove a const from a pointer use const_cast and REALLY try to avoid that.

The memory will not be leaked as string still takes ownership of it.

Upvotes: 3

Related Questions