0

I have a simple function that acts as getter for a pointer to an object

wxAuiNotebook* Frame::GetNoteBook(unsigned short index)
{
    NotebooksContainer->GetBook(index);
}

I forgot to write the return keyword in the above simple function and compiled it and it run successfully.

Then I discovered a return keyword is missing, so I launched GDB trying to know how this did work, I found the function actually returns the required pointer.


Experiment #1

I have tried much simpler example

class A {
private:
    std::string* pstr;
public:

    std::string* GetPstr()
    {
        std::cout << pstr << std::endl;
        pstr;
    }

    void SetPstr(std::string* val)
    {
        pstr = val;
    }

};

int main() {

    A a;
    std::string jfox("This is Jumping Fox");
    a.SetPstr(&jfox);
    std::cout << a.GetPstr() << std::endl;
    return 0;
}

GCC compiler doesn't throw an error during compilation, but the addresses of the objects are totally different. I got the following output under G++ 4.3.3

0x7fff547ce790
0x6012a0

Note :The same simple example throws error under MSVC 2015.


To my knowledge, some languages - ex. Ruby - return the outcome of last statement of the function as the return value, but this doesn't apply to C++.

what's the explanation why the same pointer was returned in the original example and why different pointers in the simple example ?

I'm open to more experimentation.

Community
  • 1
  • 1
Shady Atef
  • 2,121
  • 1
  • 22
  • 40
  • 7
    This is undefined behavior. – πάντα ῥεῖ Dec 23 '18 at 14:16
  • 3
    Turn on your compiler warnings, and it should warn you if control reaches the end of a non-void function. – Eljay Dec 23 '18 at 14:22
  • Not exactly a duplicate, but the currently accepted answer answers your question as well: [Why does flowing off the end of a non-void function without returning a value not produce a compiler error?](https://stackoverflow.com/questions/1610030/why-does-flowing-off-the-end-of-a-non-void-function-without-returning-a-value-no) – Suma Dec 23 '18 at 14:25
  • @Suma It may not be exactly duplicate, but it's really interesting to know about, Thanks. – Shady Atef Dec 23 '18 at 14:41

1 Answers1

3

It is an undefined behaviour. In many cases it appears like it is working, because the value to be returned is present in the expected place (like CPU register EAX on x86/x64), but this is a coincidence, nothing you could rely on.

Suma
  • 33,181
  • 16
  • 123
  • 191
  • Yup, you are right, I have considered the values of the registers and rax register holds the value of the required pointer from previous `GetBook();` call. – Shady Atef Dec 23 '18 at 14:35