Question

Does such a function result in a dangling pointer?

int *foo () {
    int a[2] = {2, 3};
    int *p = NULL;
    p = a;
    return p;
}
Was it helpful?

Solution

Yes. You are returning a pointer to an array with automatic storage duration. When the function returns the pointer is invalid.

OTHER TIPS

Never return a pointer to an automatic local variable.
In your case variable a doesn't exist once foo returns, so the pointer to it will be invalid (invokes undefined behavior).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top