2
int f(int *x)
{
    *x = 5;
    return *x;
}

int main()
{
    int * y = 0;
    int z = f(y);
}

Why does this code give me a run time error?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740

5 Answers5

10

Why does this code give me a run time error?

Because y is a NULL pointer, which is dereferenced in f(). Note, it is undefined behaviour to dereference a NULL pointer.

Can you return an integer by dereferencing a pointer?

Yes, assuming the pointer is pointing to a valid int. For example:

int main()
{
    int y = 0;
    int z = f(&y);
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Why "Technically"? It's undefined behavior, plain and simple. – Keith Thompson Mar 18 '13 at 14:45
  • @KeithThompson, he asked specifically why he was getting a runtime error and this would be the cause but it is not guaranteed to cause a runtime error. However, I will remove the "technically" as it is not useful. – hmjd Mar 18 '13 at 14:46
  • Thanks!!!! I only started learning c++ recently. Still learning the tricks of the trade. – user2182790 Mar 18 '13 at 14:46
  • Worth mentioning that a run time error is one possible consequence of undefined behavior, but is not required. – Keith Thompson Mar 18 '13 at 15:39
7

You can, if a pointer points to some valid memory. In your case, you are dereferencing a NULL (0x00) pointer, which is undefined behavior (aka UB). This, for example, works fine:

int f(int *x)
{
    *x = 5;
    return *x;
}

int main()
{
    int value = 1986;
    int *y = &value; // Point to something valid.
    int z = f(y);
}
Community
  • 1
  • 1
3

Because after int *y = 0;, y is a pointer which points to nothing (points to address 0). Your code should be like this:

int * y = new int;
*y = 0;
int z = f(y);
// ...
delete y;

or

int y = 0;
int z = f(&y);
masoud
  • 55,379
  • 16
  • 141
  • 208
1

You are setting the pointer y to 0 which makes it an NULL pointer:

int * y = 0;

and then you are trying to perform indirection on the pointer in f() here:

*x = 5;
^ 

and in the subsequent line, which is undefined behavior. If we look at the draft C++ standard section 8.3.2 References paragraph 5 says:

[...] Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by indirection through a null pointer, which causes undefined behavior. [...]

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
1

Check pointers before dereferencing and always specify error behavior:

int f(int *x)
{
   if ( x )
   {
     // do something with x
   }
   else
   {
     // do something else in case null pointer
   }
}

Dereferencing a null pointer yields a null pointer exception, such as in your case.

Ed Rowlett-Barbu
  • 1,611
  • 10
  • 27