指针是否超出范围? [英] Pointer valid out of scope?

查看:82
本文介绍了指针是否超出范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一个PDF文件,该文件指出指针超出范围后是无效的.

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

请参见以下文件中的幻灯片#14:

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

现在,我使用Dev-C ++编译器在C ++中编写了几乎完全相同的代码:

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

在原始文件中,代码使用"puts"功能打印出char字符串.它打印出垃圾.我原本希望有垃圾,但是它可以很好地打印出"Hello".奇怪的是,如果我将代码修改为:

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;

它两次打印出垃圾,表明原始的"ptr"指针已被"puts"功能修改.

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

有人可以解释一下到底发生了什么吗?为什么cout可以很好地打印出字符串(尽管有警告说返回了局部变量的地址"),即使指针被认为是无效的?为什么放置"无效?为什么推杆后推杆不起作用?为什么彗星总是落在陨石坑中?

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?

推荐答案

在您的 get_message()函数中, msg 在该函数中是本地的.函数返回后,不存在 msg .因此,使用调用者内部函数的返回值会调用未定义行为.

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,一旦您打到UB,就绝对不能保证任何输出与您的预期输出相匹配或有所偏离.

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

这篇关于指针是否超出范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆