简体   繁体   中英

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. This is b/c abc went out of scope and got destroyed after call to func() completed. Is this understanding correct ?

You have a problem in func1() . It's defined to return a std::string but there is no return statement anywhere in the function. 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.

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

func1 is supposed to return a string -- an object associated with a destructor, but you're failing to return one. (compile with -Wall to get a warning about that).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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