0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C,C++の安全なメモリ解放

Last updated at Posted at 2021-03-04

メモリ解放で気をつけることは、

  • メモリの参照を失わないこと
  • 多重開放を行わないこと
class Hoge
{
private:
    void *m_buffer_ptr;
public:
    Hoge():m_buffer_ptr( nullptr ){}
    int init( size_t size )
    {
        if( m_buffer_ptr ){
            free( m_buffer_ptr );
        }
        m_buffer_ptr = malloc( size ); // 注意:事前に開放していなけれは、この代入で参照を失いリークする
        if( !m_buffer_ptr ){
            return -1;
        }
        return 1;
    }
    void term()
    {
        if( m_buffer_ptr ){
            free( m_buffer_ptr );
            m_buffer_pter = nullptr; // 多重開放を防ぐために、ヌルを入れる
        }
    }
}

参考/元ネタ:
MEM31-C. 動的に割り当てられたメモリは一度だけ解放する
https://www.jpcert.or.jp/sc-rules/c-mem31-c.html

MEM01-C. free() した直後のポインタには新しい値を代入する
https://www.jpcert.or.jp/sc-rules/c-mem01-c.html

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?