Frage

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

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top