简体   繁体   English

局部变量作为函数调用的参数

[英]Local variable as an argument to function call

# include <iostream>
# include <string>
using std::string;
using std::cout;
using std::endl;

string func() {

    string abc = "some string";
    return abc;

}

string func1(string s) {

    cout << "I got this: " << s << endl;

} 

int main() {

    func1(func());
}

This gives: 这给出:

$ ./a.out 
I got this: some string
Segmentation fault (core dumped)

The seg fault happens b/c I am trying to access parameter s that has not been initialized properly. 段错误发生在b / c上,我正在尝试访问未正确初始化的参数s This is b/c abc went out of scope and got destroyed after call to func() completed. 这是b / c abc超出范围并在对func()调用完成后被销毁。 Is this understanding correct ? 这种理解正确吗?

You have a problem in func1() . 您在func1()遇到问题。 It's defined to return a std::string but there is no return statement anywhere in the function. 它的定义是返回一个std::string但是函数中的任何地方都没有return语句。 That is undefined behavior and the probable cause of the segfault. 这是未定义的行为,也是段错误的可能原因。 Fix that and the rest of the code should work okay. 修复该问题,其余代码应正常工作。

No, your understanding is wrong. 不,您的理解是错误的。

abc went out of scope, but that's not a problem since you're returning a copy of it. abc超出范围,但这不是问题,因为您要返回它的副本。

Look here: 看这里:

string func1(string s) {
    cout << "I got this: " << s << endl;
} 

You say the function is going to return a string but you don't return anything. 您说该函数将返回一个string但不返回任何内容。
The problem occurs when the program tries to destroy the string you didn't return, because destroying something that doesn't exist is very problematic. 当程序尝试销毁您未返回的字符串时,会发生问题,因为销毁不存在的内容非常有问题。

A reasonable compiler should warn you about this. 合理的编译器应对此发出警告。

You need to either return a string, or declare the return value void . 您需要返回一个字符串,或将返回值声明为void

func1 is supposed to return a string -- an object associated with a destructor, but you're failing to return one. func1应该返回一个string -与析构函数关联的对象,但是您无法返回一个string (compile with -Wall to get a warning about that). (使用-Wall进行编译以获得有关此的警告)。

Consequently when the destructor for the string (NOT) returned by func1 gets called at the end of main scope, it'll be working with a string object whose memory is garbage and that'll most likely result in a segfault. 因此,当func1返回的字符串(NOT)的析构函数在main作用域的末尾被调用时,它将与内存垃圾的字符串对象一起工作,并且很可能会导致段错误。

Indeed, if you compile the program with g++ on linux and run it under gdb you'll get a segfault occuring in a call to free -- which is presumably, std::string's destructor trying to free an invalid object. 确实,如果您在Linux上使用g ++编译程序并在gdb下运行它,则会在调用free时发生段错误-大概是std :: string的析构函数试图释放无效对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM