os/ossrv/genericopenlibs/cppstdlib/test/runtime/src/new_handler_test.cpp
author sl
Tue, 10 Jun 2014 14:32:02 +0200
changeset 1 260cb5ec6c19
permissions -rw-r--r--
Update contrib.
     1 // Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
     2 // All rights reserved.
     3 // This component and the accompanying materials are made available
     4 // under the terms of "Eclipse Public License v1.0"
     5 // which accompanies this distribution, and is available
     6 // at the URL "http://www.eclipse.org/legal/epl-v10.html".
     7 //
     8 // Initial Contributors:
     9 // Nokia Corporation - initial contribution.
    10 //
    11 // Contributors:
    12 //
    13 // Description:
    14 // Name        : new_handler_test.cpp
    15 // Part of     : standard c++ tests.
    16 // 
    17 //
    18 
    19 #include <new>
    20 #include "test_decls.h"
    21 
    22 int one_huge_chunk = 0xa000;
    23 int *last_huge_chunk=NULL;
    24 
    25 int glob_val = 0;
    26 void foo()
    27 {
    28 	/*
    29 	 * This is the new handler and it frees the last successful alloc so
    30 	 * that the allocation in operator new has some free memory.
    31 	 */
    32 	glob_val++;
    33 	delete [] last_huge_chunk;
    34 
    35 }
    36 
    37 void bar()
    38 {
    39 	last_huge_chunk	= new int[one_huge_chunk];
    40 }
    41 
    42 int main()
    43 {
    44 	std::new_handler h_old, h_new;
    45 
    46 	try{
    47 		while(1){
    48 			// Keep allocating until we reach OOM condition. At OOM
    49 			// the default new handler throws std::bad_alloc
    50 			bar();
    51 		}
    52 	}catch(std::bad_alloc ba)
    53 		{
    54 		}
    55 	
    56 	/*
    57 	 * Once the handler is set, failure of 'new' will call the handler to
    58 	 * get some free memory... 
    59 	 */
    60 	h_new = (std::new_handler)&foo;
    61 
    62 	h_old = std::set_new_handler(h_new);
    63 
    64 	try {
    65 	/*
    66 	 * Try once more to see if our handler actually freed up  some memory
    67 	 */
    68 		bar();
    69 	}catch(...){
    70 		glob_val = 0;
    71 	}
    72 	
    73 	CPP_TESTS_ASSERT_ALLWAYS(glob_val != 0);
    74 
    75 	h_new = std::set_new_handler(h_old);
    76 	return 0;
    77 }