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?
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().
When you assign a const char * pointer to a constant string like "hey" in the example, the hey\0 sequence is stored as a static variable inside the binary itself. It cannot be deleted, and should not be manipulated. Depending on the architecture/operating system, it may segfault when manipulated.
If you were to do const char[] tmp = "hey" then the data would be stored on the stack, and may be manipulated (but not deleted, as it will be freed once the stack clears: when the function returns).
Do not delete[] anything that isn't new[]'d.
The "hey" is a string literal and is stored in the executable's data segment, which is mapped into memory of the process at load time. The particular part where literals live is mapped read-only. Here's a snippet of the assembly produced from your code with g++ -S:
...
.section .rodata
.LC0:
.string "hey"
.text
.align 2
...
So the data is indeed read-only, and attempt to manipulate it with delete leads to segfault.
const char *tmp="hey";
"hey" is stored in a read-only area of the Data Segment. When the application starts up "hey" will be mapped to the READ-ONLY memory page.
const char *tmp="hey";
delete [] tmp;
delete will access and change some allocation metadata.,
but "hey" in the READ-ONLY memory page.
Changing value in READ-ONLY is not allowed, so segmentation fault happened.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With