Local variable as an argument to function call

1391 views c++
-1

# 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 ?

answered question

It's probably because func1 is supposed to return a string but isn't. I wouldn't expect that to cause a Segfault though. It should be perfectly fine to return abc.

3 Answers

8

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.

posted this
8

No, your understanding is wrong. 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.

posted this
13

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.

posted this

Have an answer?

JD

Please login first before posting an answer.