0

I caught an interesting bug. I have a shared pointer that I forgot to return from a function, and it appears the destructor was called for the object, and I believe the memory on which the destructor was called was junk:

struct MySharedPointer
{
    MySharedPointer() : ptr(nullptr) {}
    int ref_count = 0;
    char* ptr;
    void reset()
    {
        if (!ptr) return;
        
        // CHECK IF REFERENCE COUNT IS HIGHER THAN ZERO.
        // THIS POINTER IS STILL HOLDING IT SO IT MUST BE GREATER THAN ZERO 
        // BUT IT ISN'T, I BELIEVE IT HAS JUNK VALUE 

        delete ptr;
    }
    ~MySharedPointer()
    {
        reset();
    }
};

MySharedPointer myfunc()
{
    std::cout << "Hello";
    // I didn't return here
}

int main()
{
    myfunc();
}

I know this is plainly an error, but I would like to understand what is happening. Is it the case that it's what I suspect, that because I didn't return a value the destructor is simply being called on blank/junk/uninitialised memory? In the example I gave the compiler caught that I wasn't returning a value, but in my program it didn't catch it.

Zebrafish
  • 11,682
  • 3
  • 43
  • 119
  • 4
    Welcome to undefined behavior land. You promised `myfunc` would return a `MySharedPointer`, but you broke that promise, now the compiler breaks you ;) – NathanOliver Jan 23 '23 at 14:10
  • 5
    Returning nothing from `MySharedPointer myfunc()` (a) should give you a compilation warning/error (check compiler warning level) and (b) is Undefined Behaviour. See for compiler warnings - live - https://godbolt.org/z/fn8KvY717 – Richard Critten Jan 23 '23 at 14:10
  • 1
    *"Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has UB."* – Jason Jan 23 '23 at 14:14
  • 1
    There's no way for your program to catch the problem at run time. If you have the compiler warnings enabled, your compiler should be able to warn you about the problem at compile time. – Eljay Jan 23 '23 at 14:16
  • As others have mentioned this is undefined behavior. The only way to figure out what's going on is to look at the Assembly Code. If you're using g++ pass in the -S flag when compiling. – Alexander Richter Jan 23 '23 at 14:27
  • shared pointers are generally not a good idea - implementing them while learning C++ even less so – Neil Butterworth Jan 23 '23 at 14:31
  • @NeilButterworth Why aren't they a good idea? What's wrong with them? I need reference counting to objects. – Zebrafish Jan 24 '23 at 12:58

0 Answers0