わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。

newのメモリ確保失敗を検知する(std::bad_alloc)

newでメモリの確保に失敗した場合は例外(std::bad_alloc)がthrowされます。この例外をcatchする事でnewでのメモリ確保失敗を検知できます。

newのメモリ確保失敗を検知する(std::bad_alloc)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <locale.h>
#include <windows.h>
 
 
 
/*
    newのメモリ確保失敗を検知する(std::bad_alloc)
*/
int _tmain
(
      int argc
    , _TCHAR* argv[]
)
{
    /*
        ロケールを日本に設定
         これを設定するだけで、標準出力に日本語が表示される
         ようになります。
    */
    setlocale( LC_ALL, "Japanese" );
 
    try {
 
        // メモリの確保
        char* cpMemory = new char[ 0x7fffffff ];
 
        // メモリの解放
        delete [] cpMemory;
     
    } catch( std::bad_alloc& err ) {
 
        // メモリ確保失敗
        std::wcout << L"メモリ確保に失敗しました。" << err.what() << std::endl;
 
    }
 
    // 正常終了
    return( 0 );
}

実行結果

メモリ確保に失敗しました。bad allocation






わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。