小さい頃はエラ呼吸

いつのまにやら肺で呼吸をしています。


【cppcheck】error: Memory is allocated but not initialized: xxx

はじめに

C++の静的解析ツール「cppcheck」でソースコードを静的解析した場合に、以下の警告がでることがあります。

error: Memory is allocated but not initialized: xxx

cppcheckのバージョン
  • v1.66
サンプルプログラム

以下のソースプログラムを解析にかけると表示されます。

#include "stdafx.h"
#include <windows.h>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

int _tmain(int argc, _TCHAR *argv[])
{

  char* hoge;
  hoge = (char*)malloc(10);  // -> error: Memory is allocated but not initialized: hoge
  //memset(hoge, 0, 10); // -> OK
  char szBuff[256] = { 0 };
  printf("%s\n", hoge);

  _CrtDumpMemoryLeaks();
  return 0;

}

上記のように、malloc関数を呼び出した際、アロケートした領域を初期化していない場合に警告が出力されます。