Is it necessary to release memory for a string variable defined inside a function in C++?

Viewed 168

Problem description:

It is needed in C to delete the allocated memory for a pointer to an array char * (how we can define string in C).

My question:

I am wondering if it is also necessary for C++ string types.

For example:

Let's say I have a function which is responsible for converting all uppercase characters to lowercase like below.

string convertToLowerCase(string str) {
  string res = str;
  for (int i=0; i<str.length();++i) {
    res[i]= tolower(str[i]);
  }
  return res;
}
  • After calling this function for comparing two strings, I do not need to de-allocate the return string variable of the convertToLowerCase function on the caller side.
  • My understanding is that the memory de-allocation is done in C++ string type.
  • Please correct me if I am wrong.
2 Answers

string type,defined as char *

char* is merely a pointer. It is not a string. It can point to a character within a string though.

I understand in C we need to delete any memory allocation for string type

You (usually) need to deallocate all memory that you allocate, regardless of what type you allocate the memory for. This applies to both languages.

My assumption is that the memory de-allocation in done in C++ String type, but please correct me if i am wrong.

Your assumption is not wrong. Well designed classes deallocate what they allocate.

Setting compiler optimizations aside for the moment for simplicity, in C++, you can assume that when an object, like an instance of a string, goes out of scope, its destructor is called. If the class of which that object is an instance is well-written, then you can assume that any memory allocated by the class will be freed in the calling of destructor. The returned object will be copied into the variable at the calling site of the function before the destructor is called on the returned object.

Compiler optimizations such as RVO can cause different behavior, but this is I think a good conceptual starting point.

Related