Вопрос

Does such a function result in a dangling pointer?

int *foo () {
    int a[2] = {2, 3};
    int *p = NULL;
    p = a;
    return p;
}
Это было полезно?

Решение

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

Другие советы

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).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top