ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Dynamic Memory Allocation and Memory Leak
    C++ 2014. 3. 2. 06:59

     

    동적인 메모리는 runtime에 가변적인 크기를 갖는 메모리를 사용할 때 필수적인 메모리 사용방법이다.

    동적인 메모리는 스택에 생성이 되는 데 메모리의 유실을 방지하기 위하여 몇가지 주의 사항이 있다.

    1. 대입연산자, 대입 이동연산자는  operator overloading을 해서 private으로 막아서 다른 프로그램에서 사용하지 못하도록 막는다. 이것은 서로 다른 사이즈의 메모리가 할당된 객체간의 데이타 복사를 막기위한 것이다.

      private:

          int mWidth;

          int mHeight;

          CellPiece** mCell;

              

          void CopyFrom(const Fruit& src) throw (bad_alloc);

          void MoveFrom(Fruit& src);

          Fruit& operator=(const Fruit& rhs) throw (bad_alloc);

          Fruit& operator=(Fruit&& rhs);

    2. 아니면 원본 메모리를 삭제하고 새로 재생성하는 방법으로 overloading을 해도 된다.

      Fruit& Fruit::operator=(const Fruit& rhs)

      for (int i=0;i<mWidth;++i)

      delete []mCell[i];

      delete []mCell;

      mCell = nullptr;

    3. 동적으로 할당된 메모리의 포인터는 반드시 shared_ptr 로 저장을 한다.

          shared_ptr<Fruit> f5(new Fruit());

          f5->setCellAt(1,1,"smartptr");

          cout << f5->getCellAt(1,1) << endl;

       

          auto f6 = make_shared<Fruit>(50,50);

          f6->setCellAt(10,1,"make_shar");

          cout << f6->getCellAt(10,1) << endl;

    4. Visual Studio 에서 메모리 릭을 찾는 방법

      #define _CRTDBG_MAP_ALLOC

      #include <stdlib.h>

      #include <crtdbg.h>

      #include <new>

       

       

      #ifdef _DEBUG

      #ifdef DEB_NEW

      #define DEB_NEW new (_NORMAL_BLOCK, __FILE__, __LINE__)

      #define new DEB_NEW

      #endif

      #endif

      #define DEF_WIDTH 100

      #define DEF_HEIGHT 100

        Main() function에서

        _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

    반드시 Debug 모두로 수행을 해야 한다.

    'C++' 카테고리의 다른 글

    Volitile Keyword  (0) 2014.03.09
    Object Pool  (0) 2014.03.09
    Rvalue reference (우측값 참조)  (0) 2014.02.28
    Rambda Expression  (0) 2014.02.26
    string class operator overloding  (0) 2014.02.26
Designed by Tistory.