Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char* 's in C++

Tags:

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?

like image 973
Pyjong Avatar asked Jan 04 '10 18:01

Pyjong


4 Answers

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().

like image 185
Nick Bastin Avatar answered Oct 06 '22 23:10

Nick Bastin


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.

like image 29
Sufian Avatar answered Oct 07 '22 01:10

Sufian


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.

like image 28
Nikolai Fetissov Avatar answered Oct 07 '22 00:10

Nikolai Fetissov


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.

like image 42
whunmr Avatar answered Oct 06 '22 23:10

whunmr