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?
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?
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);
}
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);
}
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);
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. [...]
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.