Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you return an integer by dereferencing a pointer?

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?

like image 439
user2182790 Avatar asked Aug 01 '26 08:08

user2182790


2 Answers

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);
}
like image 63
hmjd Avatar answered Aug 03 '26 22:08

hmjd


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);
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!