sl@0: // Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). sl@0: // All rights reserved. sl@0: // This component and the accompanying materials are made available sl@0: // under the terms of "Eclipse Public License v1.0" sl@0: // which accompanies this distribution, and is available sl@0: // at the URL "http://www.eclipse.org/legal/epl-v10.html". sl@0: // sl@0: // Initial Contributors: sl@0: // Nokia Corporation - initial contribution. sl@0: // sl@0: // Contributors: sl@0: // sl@0: // Description: sl@0: // Name : new_handler_test.cpp sl@0: // Part of : standard c++ tests. sl@0: // sl@0: // sl@0: sl@0: #include sl@0: #include "test_decls.h" sl@0: sl@0: int one_huge_chunk = 0xa000; sl@0: int *last_huge_chunk=NULL; sl@0: sl@0: int glob_val = 0; sl@0: void foo() sl@0: { sl@0: /* sl@0: * This is the new handler and it frees the last successful alloc so sl@0: * that the allocation in operator new has some free memory. sl@0: */ sl@0: glob_val++; sl@0: delete [] last_huge_chunk; sl@0: sl@0: } sl@0: sl@0: void bar() sl@0: { sl@0: last_huge_chunk = new int[one_huge_chunk]; sl@0: } sl@0: sl@0: int main() sl@0: { sl@0: std::new_handler h_old, h_new; sl@0: sl@0: try{ sl@0: while(1){ sl@0: // Keep allocating until we reach OOM condition. At OOM sl@0: // the default new handler throws std::bad_alloc sl@0: bar(); sl@0: } sl@0: }catch(std::bad_alloc ba) sl@0: { sl@0: } sl@0: sl@0: /* sl@0: * Once the handler is set, failure of 'new' will call the handler to sl@0: * get some free memory... sl@0: */ sl@0: h_new = (std::new_handler)&foo; sl@0: sl@0: h_old = std::set_new_handler(h_new); sl@0: sl@0: try { sl@0: /* sl@0: * Try once more to see if our handler actually freed up some memory sl@0: */ sl@0: bar(); sl@0: }catch(...){ sl@0: glob_val = 0; sl@0: } sl@0: sl@0: CPP_TESTS_ASSERT_ALLWAYS(glob_val != 0); sl@0: sl@0: h_new = std::set_new_handler(h_old); sl@0: return 0; sl@0: }