Const char * in C ++

How do string expressions work in C ++?

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 expression "hey" stored and why does a segmentation error occur when trying to delete it?

+3
source share
9 answers

Where it is stored is left to the compiler to make a decision in this (somewhat special) case. However, this does not matter to you - if you do not allocate memory with new, it is not very pleasant to try to free it with delete. You cannot allocate deletememory the way you allocated it.

If you want to control the release of this resource, you must use std::stringor allocate a buffer with malloc().

+17

const char * "hey" hey\0 . , . / , .

const char[] tmp = "hey", ( , : ).

delete[] , new[] 'd.

+16

"hey" - , . , , . , g++ -S:


...
    .section    .rodata
.LC0:
    .string "hey"
    .text
    .align 2
...

, , delete segfault.

+10

const char *tmp="hey";

"hey" . , "" READ-ONLY.

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

delete ., "" READ-ONLY.

READ-ONLY , .

+5

: .

+4

, .

"hey" "hey" - , ( "hey" ). char *. 4 . 'h', 'e', โ€‹โ€‹'y' 0 (0 - ( ) C.

: " ".

.

std::string ( "hey" ), - .

+4

. delete[] tmp, new char[stringSize].

+1

new . , new delete, malloc free. , - .

, , , .

+1

"hey" , , , , .

, , , , :

#include <iostream>
using namespace std;

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

    const char *hey="hey";
    char* tmp=new char[4]; // NB allocate 4 chars for "hey" plus a null terminator
    strcpy(tmp,hey);  // copies the string and null terminator
    cout << tmp << endl;
    delete [] tmp;
    // must not use tmp now as it points to deallocated memory
    // must not delete hey

    return 0;
}

Notice how I managed to remove the memory new'd using tmp. I could do this:

    cout << tmp << endl;
    hey = tmp;
    delete [] hey;

It doesn't matter if we end up pointing to the new'd memory with heyor tmpuntil we delete it correctly to avoid memory leaks.

0
source

Source: https://habr.com/ru/post/1727266/


All Articles