3

I am getting segmentation fault in my application, and while testing with sample applications I found that object reference after freeing it not resulting segmentation fault. Below is the test code which I run,

hash_node  *node_obj=new hash_node();
delete node_obj;
node_obj->var1=0;
return 0;

I just overloaded new to use malloc and delete to use free. Can any one please advise me in this ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Binu Babu
  • 127
  • 1
  • 9

3 Answers3

4

Accessing a location in memory using a pointer that has been deleted/freed is undefined behaviour. Undefined behaviour doesn't imply that a segfault will occur.

sashang
  • 11,704
  • 6
  • 44
  • 58
0

It is an undefined behavior, so you cannot expect a segmentation fault here. You can refer Stroustrup's "Design and Evolution of C++" which says:

It is not possible to change what a reference refers to after initialization. That is, once a C++ reference is initialized it cannot be made to refer to a different object later; it cannot be re-bound. I had in the past been bitten by Algol68 references where r1=r2 can either assign through r1 to the object referred to or assign a new reference value to r1 (re-binding r1) depending on the type of r2. I wanted to avoid such problems in C++.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Segmentation fault happens when a process tries to access memory location which its not suppose to. Memory outside the area which is allotted to the process.


In your code, accessing memory already freed is Undefined Behaviour.
Haris
  • 12,120
  • 6
  • 43
  • 70