But [does] anyone know what delete[] do[es] to release memory? |
Don't know if it'll do you any good, but this is the assembly behind c++ new/delete:
1 2 3 4 5
|
call ??2@YAPAXI@Z ; Calling operator new functions
;Stuff...
call ??0X@@QAE@H@Z ; The call object constructor
;Stuff...
call ??1X@@QAE@XZ ; The destructor is called
|
http://www.programering.com/a/MDM1ETMwATc.html
A simple example code that illustrates data being read after its array has been set to null. The user will input a
valid address and the program will print the value at the address:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
void devils_advocate()
{
srand(time(0));
int *arry = new int[5];
int *safety = arry; //Safety net to release memory
//---------------------Warning-----------------
cout<<"Warning: Memory will leak if program crashes or forced exit!"<<endl<<endl;
cout<<"If so, a simple reboot will restore any memory loss this way."<<endl<<endl;
//---------------------Pretest-----------------
cout<<"Inserting 5 random integers into the array: "<<endl<<endl;
for(int i = 0 ; i < 5 ; i++) //Insert data into the array
{
arry[i]=rand()%90+10;//Example data
cout<<"Address: "<<&arry[i]<<" with a data of: "<<arry[i]<<endl;//Print data
}
cout<<endl<<endl;
cout<<"Array has been set to NULL however data will still persist..."<<endl<<endl<<endl;
arry = NULL; //Set address of arry to NULL
//---------------------Postest-----------------
int*head;
string address;
do
{
cout<<endl;
cout<<"Please enter: (A 'valid address' listed above) or ('Enter') to exit: ";
getline(cin,address);
if(address!="")
{
head=reinterpret_cast<int*>(strtol(address.c_str(),0,0));
cout<<"The data at address: "<<head<<" is "<<*head<<endl;
}
else
break;
}while(true);
delete []safety; //Release memory
cout<<"Memory freed"<<endl;
}
int main()
{
string choice;
cout<<"Choice: TEST(1) or EXIT(return key): ";
getline(cin,choice);
if(choice=="1")
devils_advocate();
else
cout<<"Exit without testing"<<endl;
return 0;
}
|
After
arry = NULL;
the data(s) would still persist at their respective addresses.
Even if we were to remove:
int *safety = arry;
and
delete []safety;
,having no pointers associating with the memory, the data would still persist when we later access those addresses.
However, if we were to call
delete []safety;
before line 29, we would get undefined behaviors. The data will become garbage while the addresses would still be accessible, however there are possibilities that others may reserving that specific memory.
Warnings:
In the above code, if you are to enter an invalid address, a segmentation fault will occur and you will be leaking memory. Same applies to ending the program early; do not force exit with ctrl-c.
If you do leak memory, you can regain your memory on your next reboot.