c++ - What does Visual Studio do with a deleted pointer and why? -


a c++ book have been reading states when pointer deleted using delete operator memory @ location pointing "freed" , can overwritten. states pointer continue point same location until reassigned or set null.

in visual studio 2012 however; doesn't seem case!

example:

#include <iostream>  using namespace std;  int main() {     int* ptr = new int;     cout << "ptr = " << ptr << endl;     delete ptr;     cout << "ptr = " << ptr << endl;      system("pause");      return 0; } 

when compile , run program following output:

ptr = 0050bc10 ptr = 00008123 press key continue.... 

clearly address pointer pointing changes when delete called!

why happening? have visual studio specifically?

and if delete can change address pointing anyways, why wouldn't delete automatically set pointer null instead of random address?

i noticed address stored in ptr being overwritten 00008123...

this seemed odd, did little digging , found microsoft blog post containing section discussing "automated pointer sanitization when deleting c++ objects".

...checks null common code construct meaning existing check null combined using null sanitization value fortuitously hide genuine memory safety issue root cause needs addressing.

for reason have chosen 0x8123 sanitization value – operating system perspective in same memory page 0 address (null), access violation @ 0x8123 better stand out developer needing more detailed attention.

not explain visual studio pointer after deleted, answers why chose not set null automatically!


this "feature" enabled part of "sdl checks" setting. enable/disable go to: project -> properties -> configuration properties -> c/c++ -> general -> sdl checks

to confirm this:

changing setting , rerunning same code produces following output:

ptr = 007cbc10 ptr = 007cbc10 

"feature" in quotes because in case have 2 pointers same location, calling delete sanitize one of them. other 1 left pointing invalid location.

visual studio set sticky situation failing document flaw in design.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -