C++ Strings – Understanding const char*

c++string

How does string expressions in C++ work?

Consider:

#include <iostream>
using namespace std;

int main(int argc, char *argv[]){

    const char *tmp="hey";
    delete [] tmp;

    return 0;
}

Where and how is the "hey" expression stored and why is there segmentation fault when I attempt to delete it?

Best Answer

Where it's stored is left to the compiler to decide in this (somewhat special) case. However, it doesn't really matter to you - if you don't allocate memory with new, it's not very nice to attempt to deallocate it with delete. You cannot delete memory allocated in the way you have allocated it.

If you want to control the deallocation of that resource, you should use a std::string, or allocate a buffer using malloc().

Related Question