0

new and delete operator

Hi,I still couldn't understand why are we using new and delete. Can someone please explain me clearly, thanks.

31st Dec 2017, 5:28 PM
Mustafa K.
Mustafa K. - avatar
3 Answers
+ 1
Lets say you have code like this: int *p = new int; Pointer p now stores address to 4 bytes (is size of int 4 bytes?) of allocated memory. You can store something into this allocated memory like this: *p = 665; std::cout>>*p; Now if you want to free this allocated memory, you can use delete like this: delete p; If you dont free this memory, and pointer gets out of scope, you will have no access to this memory. Example: void func() { int *p = new int; } *p = 7; //error //Pointer got deleted, but allocated memory did not. You cant access this memory now, because you dont have pointer to it. Not 100% sure if its right, but thats how I understand it.
31st Dec 2017, 7:36 PM
Null
Null - avatar
0
actually I still couldnt understand, i think i have problem with my brain šŸ˜ƒ, thanks for answer.
31st Dec 2017, 7:39 PM
Mustafa K.
Mustafa K. - avatar
0
I will try to explain it to you better. Pointer stores address (location somewhere in memory) and with "new" we basically reserve n bytes of memory and assign address of 1st byte in our memory, which we reserved to our pointer. Same example as before: int *p = new int; int *p is pointer. (Stores location in memory) new int will reserve size of int and return address of first byte
31st Dec 2017, 7:54 PM
Null
Null - avatar