Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Query on "delete" operator.

Status
Not open for further replies.

isaisa

Programmer
May 14, 2002
97
IN
Hi,
I am trying to write the code which will create the class object on the heap using the "new" operator and trying to free it using "delete" operator. The code is as follows.

/*****************************************/
class CTest {
public:
int i;
};

void main(void)
{

CTest * ct1 = new CTest;
CTest *ct2 = ct1;

delete ct1;
ct1 = NULL;

ct2->i = 900;

cout << "i= " << ct2->i << endl;

return;
}
/***************************************/

As per my understanding, i should get the access violation after the delete statement. But the code is running properly. Can you help me out in understanding the concept ?

Thanks in advance
Sanjay
 
1. Please use [code][/code] tags when posting code.

2. void main(void)
main returns an int.

3. i should get the access violation after the delete statement.
Whilst your code is indeed wrong, that you're accessing memory via a copy of a pointer which has been deleted, there is no guarantee that the system should fail because of it.

Assigning ct1 = NULL; will not affect the prior assignment of ct2 = ct1;

Mistakes like this do make it very hard to track down some memory related bugs.

--
 
Thanks Salem for the quick response.

As per your suggestion, i made the following changes in the code.

Code:
    CTest * ct1 = new CTest; 
    delete ct1;
    ct1->i = 900;
    cout << "i= " << ct1->i << endl;


The above code should give me the access violation as i am deallocating the memory with the help of "delete". But i am still able to get the output on the console as 900.

the behavior of the system is still not clear. can you please help me out ?

Thanks
sanjay
 
As usually, the C++ implementation uses sub-allocation strategy, so a (large) memory chunk obtained from the OS is in the process address space if a small suballocation was returned in a free heap subpool. So (logically) deallocated heap address (sometimes) may be accessed. Of course, it's a logical error, you can't do that...
 
You won't necessarily get an Access Violation when you do funny stuff with unallocated memory.

That is one reason such bugs can be somewhat tricky to find as they sometimes result in funny, unexplainable (at first), behavior.

/Per
[sub]
www.perfnurt.se[/sub]
 
The memory is marked for further use, but until it's used, the data remains.

Be sure that if you had important data and wanted this behaviour for any reason, then you would get an access violation for sure :)

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top