returning pointer to a local variable [duplicate]

你离开我真会死。 提交于 2021-02-17 07:06:29

问题


What happens when a pointer to a local variable is returned by a function?

for example

int* foo()
{
    int local;
    int* ptr = &local;
    return ptr;
}

will compiler issue a warning or will it compile and produce unexpected results??


回答1:


Similar kind of question has already been asked : Stack Overflow, local pointer

There are somethings in C which are left for compiler vendor to implement in the way they like. The behaviour of such things are not defined by the creators. Compiler vendors can implement such things as in the way they feel easy and faster. This falls in the same category. The behaviour is undefined and depends on the compiler you are using.

One more such thing is use of more than one pre-increment (pre-decrement) and/or post-increment (post-decrement). When the same code runs on different compilers, you'll may get different output.




回答2:


What happens when a pointer to a local variable is returned by a function?

Undefined behaviour. Anything can happen. The compiler will give you a warning.

This is g++ warning for that mistake:

g++ -Wall -std=c++11 -O3 test.cpp -o test
warning: function returns address of local variable [-Wreturn-local-addr]


来源:https://stackoverflow.com/questions/40991246/returning-pointer-to-a-local-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!