Pointer valid out of scope? [duplicate]

爷,独闯天下 提交于 2021-01-28 08:35:03

问题


There's a PDF I'm reading which says that a pointer is invalid after it passes out of scope.

See slide #14 in the file below: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-087-practical-programming-in-c-january-iap-2010/lecture-notes/MIT6_087IAP10_lec05.pdf

Now I wrote almost the exact same code below in C++ with Dev-C++ compiler:

#include <iostream>
using namespace std;

char* get_message()
{
      char msg[]="Hello";
      return msg;
}

int main()
{
    char *ptr = get_message();
    cout<<ptr<<endl;
    system("PAUSE");
    return 0;
}

In the original file, the code uses the "puts" function to print out the char string. It prints out garbage. I was expecting garbage, but it prints out "Hello" just fine. Curiously, if I amend my code to:

char *ptr = get_message();
puts(ptr);
cout<<ptr<<endl;

It prints out garbage twice, suggesting the original "ptr" pointer has been modified by the "puts" function.

Can somebody please explain exactly what is happening? Why does cout prints out the string just fine (although there's a warning saying "address of local variable returned") even though the pointer is supposed to be invalid? Why does "puts" not work? Why does cout not work after puts? Why do comets always land in craters?


回答1:


In your get_message() function, msg is local to the function. After the function returns there is no existence of msg. so, using the return value of the function inside the caller invokes undefined behavior.

FWIW, once you hit UB, there is absolutely no guarantee of any output either matching or deviating from your expected output.



来源:https://stackoverflow.com/questions/32797250/pointer-valid-out-of-scope

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