0

I spot some interesting articles about exception handle in CodeProject

http://www.codeproject.com/KB/cpp/seexception.aspx

After reading, I decided to do some experiment.

The first time I try to execute the following code

char *p;
p[0] = 0;

The program died without question.

But

After several times when I executed the same problem binary code, it magically did fine.

Even the following code is doing well. Any clue or explanation?

char *p;
p[1000] = 'd';
cout<<p[1000]<<endl;

My O/S is Windows 7 64bit and compiler is VS2008 rc1.

Level 2
  • 3
  • 2
  • See [What exactly do "IB" and "UB" mean?](http://stackoverflow.com/questions/2766731/what-exactly-do-ib-and-ub-mean). Quoting the accepted answer, "Using undefined behaviour is nearly always a bad idea. Even if it seems to work sometimes, any change to environment, compiler or platform can randomly break your code." – Matthew Flaschen Jun 17 '10 at 04:44
  • 1
    Address space layout randomization (ASLR) sometimes hides bugs. – Jonathan Leffler Jun 17 '10 at 05:00

1 Answers1

1

Dereferencing a pointer that doesn't point to an object (for example, an uninitialized pointer) results in undefined behavior.

This means that anything can happen. Typically, writing via an uninitialized pointer will cause your program to crash--either immediately or at some point in the future. It is conceivable that your program could appear to continue running correctly, but you can never rely on that.

James McNellis
  • 348,265
  • 75
  • 913
  • 977