0

I did some test in vs2012 with codes below:

In Debug Mode:

int *b; int *a = b;   //  Crash!!
int *b = *(new int*); int *a = b;  //this is ok

I'm curious why it's like this. Does the (new int*) points to some real memory by default? And Since it is runs in non-debug mode,, so I wonder if it is ok to write such code

Jilin
  • 291
  • 1
  • 2
  • 12

1 Answers1

1

I'm curious why it's like this.

Both have undefined behaviour due to using the value of an uninitialised object. While it's surprising that this should crash, there's no reason to assume it won't go wrong in some unpredictable way.

Dereferencing the uninitialised pointer (e.g. int a = *b; rather than int *a = b;), would be more likely to cause a crash. Are you sure you weren't doing that?

Does the (new int*) points to some real memory by default?

The int** returned by new int* does. The int* that it points to is uninitialised.

if it is ok to write such code

It's never OK to write code with undefined behaviour. Even if it appears to "work", it will come back to bite you when you least expect it.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 1
    Regarding the first example, I could not find any relevant reference which would make it UB. The closest I came across is 4.1.1 `If the object to which the glvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior.` (conv.lval) - from n3242 (C++11 draft). Are you suggesting `int *a = b` is an `lvalue to rvalue conversion?` – Abhijit Jan 13 '14 at 10:57
  • @Abhijit: Yes, that's right. `b` is an _lvalue_, and must be converted to an _rvalue_ to use its value. – Mike Seymour Jan 13 '14 at 10:59