Delete pointers

I wanted to ask, dynamically creates a pointer, and then changes the address of the pointer to something else, while still removing the original allocated space?

eg:

int main()
{

int c = 50;
    // Memory leak
    int * q = new int;
    q = & c;
    delete q;
}

What exactly is being removed or is occurring?

Thank!

+4
source share
5 answers

dynamically creates a pointer and then changes the address of the pointer to another while still deleting the original allocated space?

No. deletewill free the memory pointed to by its operands. You need deletethe same memory block that you received from new.

int c = 50;
int * q = new int;
int * r = q;
q = & c;
delete q;     // WRONG! q points to something you didn't get from new
delete r;     // OK! p points to the block you got from new

, delete , , , . r , q new, delete . q , , new, delete .

, q, , q :

int c = 50;
int * q = new int;
*q = c;
delete q;     // OK! q still points to the same place

, , q , q. q - , new, delete.

+4

undefined.

q = & c;, , new int. , , .

delete q; ( q &c), , , , , . undefined.


, , . int. , c++11 ( boost, c++11). , raw c. " ++ Chapter 4".

+7

() c. - C/++. delete , , , ( delete , new, ) , .

, , ( ) , , , , . , c , .

+3

, c. , , , q .

+1

: -

,

. - , C ++. , , . .

, , / . /, , . / O/S , . . .

+1
source

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


All Articles