-4

I am pretty new to C++, and while getting started I got stuck on a frustrating problem concerning pointers. Consider the following code:

#include <iostream>
using namespace std;

int main (){

     int* mypointer;
     *mypointer = 1;

      cout << "Whats wrong";
}

It crashes during runtime. I suspect it has to do with the pointer assignment. But after commenting out the cout statement, the program executes. By assigning the pointer as

int* mypointer, myvar;
myvar = 1;
mypointer = &myvar;

the program runs, and I can print the value of the pointer as:

cout << "value of pointer: " << *mypointer;

I draw the conclusion that this would be the correct usage of a pointer.

BUT: Why does the following code execute??:

#include <iostream>
#include <stdio.h>
using namespace std;

int main (){

    int* mypointer;
    *mypointer = 1;

    printf("This works!\n");
    printf("I can even print the value mypointer is pointing to: %i",*mypointer);
}

Simply using printf?? I would really appreciate an explanation guys!

  • 5
    I'd suggest holding back for now and reading good C++ book instead of blindly typing. Here is list of recommended C++ books http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Tomasz Plaskota Apr 26 '17 at 12:26
  • @TomaszPlaskota: I'm not sure that's called for. The OP has performed a pretty good investigation here, and actually come to the _correct_ conclusion on how to fix the code.... but now has a completely warranted question about why something is appearing to run when it theoretically shouldn't. The only missing link is the scope of what is "allowed" and expected to happen when you have UB. – Lightness Races in Orbit Apr 26 '17 at 12:30

1 Answers1

2

The code executes because, just by chance, your compiler has managed to optimise the program down enough that the 1 is "hardcoded" into the printf call.

It would probably have done this anyway, rendering both the original int and the pointer irrelevant, but in this instance it's not reflecting the fact that the pointer was broken and there wasn't an original int.

so, strictly speaking, this doesn't even reflect the semantics of the program: as you've spotted, assigning a value to an int that doesn't exist (through an uninitialised or otherwise invalid pointer) is nonsense and results in undefined behaviour.

But that's the nature of undefined behaviour: anything can happen! The authors of your compiler are making the most of that, by realising that they don't have to write any code to make this case work logically. Because it's you who violated the C++ contract. :)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055