Memory leak prevention (case-specific)

Consider the following situation:

SomeType *sptr = someFunction();
// do sth with sptr

I do not know the internal elements of someFunction (). Its pretty obvious that the pointer to the object returned by someFunction () must be either malloc'ed or a static variable.

Now I am doing something with sptr and am leaving. it is clear that the object is still on the heap, which is possibly the source of the leak.

How can I avoid this?

EDIT:

Are links safer than pointers. Call the destructor for SomeType if I do this:

{
  SomeType &sref = *sptr;
}

Any ideas.

+3
source share
6 answers

someFunction. someFunction ( delete someFunction), , - ).

, .

+19

? ? , . , - (, ) .

, , , , ( ), , (, ).

, , - , . , , , .

, , , , . , , , , , . .

+3

, , OS ;

IDE .

? , , , someFunction(), , , , API , .

Max

0

. , release, , ( , *) .

( ) ( ) , . .

0

someFunction , someFunctionFree, , SomeType. someFunction ( ). ( CreateObject/DestroyObject).

0

Like others, pay attention to the function to enforce ownership assumptions in the code. Here is one way to do this with smart pointers :

#include <iostream>
#include <boost/shared_ptr.hpp>

struct Foo
{ 
  Foo( int _x ) : x(_x) {}
  ~Foo() { std::cout << "Destructing a Foo with x=" << std::hex << x << "\n"; }
  int x;
};

typedef boost::shared_ptr<Foo> FooHandle;

FooHandle makeFoo(int _x = 0xDEADBEEF) {
    return FooHandle(new Foo(_x));
}

int main()
{
    {
        FooHandle fh = makeFoo();
    }
    std::cout<<"No memory leaks here!\n";

    return 0;
}
0
source

Source: https://habr.com/ru/post/1751070/


All Articles