Search code examples
c++pointersmemory-leaksvalgrindeclipse-cdt

using free(const char *) in c++ 11


In one of my c++ functions I am calling ab demangle. I want to deallocate result after changing that to string. Here is the code:

const char *  realName;
string name;
const std::type_info &ti = typeid(*this);
realName = abi::__cxa_demangle(ti.name(), 0, 0, &status);

name= realName;
int index =name.find_last_of(':');
name = name.substr(index+1, name.length()-index-1);
free((void *) realName);

The code is running without problem but eclipse compiler is not happy and showing an error for using free: "Function 'free' could not be resolved".

I tried to use delete instead of free.

delete realName;

The code is running without problem and eclipse compiler is happy, however when I am profiling code with valgrind, I am getting a profiling error: Mismatched free() / delete / delete []

So my question is: 1- Should I use free in c++ or shall I use just delete, delete [] 2- If I should not use free why valgrind giving me an error 3- If I should use free why eclipse cdt comipler is giving me a compile error but when I am running code everything is ok. 4- is my code has correct style based on c++11? or is it a combination of c and old c++?


Solution

  • Should I use free in C++ or shall I use just delete, delete[]?

    You should use the function or the operator that matches the allocation. When you allocate memory for your own use, you should use new/new[] for allocation, and delete/delete[] for deallocation.

    When the memory to be deallocated comes from other sources, such as __cxa_demangle, you should read the documentation to see what functionality needs to be used on deallocation. The documentation for your function states that

    the demangled name is placed in a region of memory allocated with malloc.

    Therefore, you must use free to free it.

    If I should use free why Eclipse cdt compiler is giving me a compile error but when I am running code everything is OK.

    Function free is defined in <cstdlib> header. You need to add this header to your cpp file to make sure you code compiles fine.