Question

Here is the code, The program leads to memory leak. I do not know how it happen?

#include <iostream>
#include <memory>
#include <stdexcept>
using namespace std;

void test(shared_ptr<string> &ptr, int num) {
    cout << "pass test:" << *ptr << " " << num << endl;
}

int fun() {
    throw new runtime_error("runtime error");
    return 0;
}

int main() {

    try {
      //  test(static_cast<shared_ptr<string> >(new string("hello")), fun());
      //  Solution
      shared_ptr<string> sps(new string("h"));
      test (sps, fun());
    } catch (runtime_error *e) {
        cout << e->what() << endl;
    }
    return 0;
}

I use valgrind to test memory leak.

==4726== 
==4726== HEAP SUMMARY:
==4726==     in use at exit: 54 bytes in 2 blocks
==4726==   total heap usage: 6 allocs, 4 frees, 248 bytes allocated
==4726== 
==4726== LEAK SUMMARY:
==4726==    definitely lost: 16 bytes in 1 blocks
==4726==    indirectly lost: 38 bytes in 1 blocks
==4726==      possibly lost: 0 bytes in 0 blocks
==4726==    still reachable: 0 bytes in 0 blocks
==4726==         suppressed: 0 bytes in 0 blocks
==4726== Rerun with --leak-check=full to see details of leaked memory
==4726== 
==4726== For counts of detected and suppressed errors, rerun with: -v
==4726== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

I think sps will delete itself when excption is evoked by fun(). What's more, the reference to shared_ptr in test() will not allocate memory at not.

The behavior of smart pointer is weird.

Was it helpful?

Solution

The exception is your leak. You are instantiating it and not deleting. Look at this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top