1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/os/ossrv/genericopenlibs/cppstdlib/test/runtime/src/new_handler_test.cpp Fri Jun 15 03:10:57 2012 +0200
1.3 @@ -0,0 +1,77 @@
1.4 +// Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
1.5 +// All rights reserved.
1.6 +// This component and the accompanying materials are made available
1.7 +// under the terms of "Eclipse Public License v1.0"
1.8 +// which accompanies this distribution, and is available
1.9 +// at the URL "http://www.eclipse.org/legal/epl-v10.html".
1.10 +//
1.11 +// Initial Contributors:
1.12 +// Nokia Corporation - initial contribution.
1.13 +//
1.14 +// Contributors:
1.15 +//
1.16 +// Description:
1.17 +// Name : new_handler_test.cpp
1.18 +// Part of : standard c++ tests.
1.19 +//
1.20 +//
1.21 +
1.22 +#include <new>
1.23 +#include "test_decls.h"
1.24 +
1.25 +int one_huge_chunk = 0xa000;
1.26 +int *last_huge_chunk=NULL;
1.27 +
1.28 +int glob_val = 0;
1.29 +void foo()
1.30 +{
1.31 + /*
1.32 + * This is the new handler and it frees the last successful alloc so
1.33 + * that the allocation in operator new has some free memory.
1.34 + */
1.35 + glob_val++;
1.36 + delete [] last_huge_chunk;
1.37 +
1.38 +}
1.39 +
1.40 +void bar()
1.41 +{
1.42 + last_huge_chunk = new int[one_huge_chunk];
1.43 +}
1.44 +
1.45 +int main()
1.46 +{
1.47 + std::new_handler h_old, h_new;
1.48 +
1.49 + try{
1.50 + while(1){
1.51 + // Keep allocating until we reach OOM condition. At OOM
1.52 + // the default new handler throws std::bad_alloc
1.53 + bar();
1.54 + }
1.55 + }catch(std::bad_alloc ba)
1.56 + {
1.57 + }
1.58 +
1.59 + /*
1.60 + * Once the handler is set, failure of 'new' will call the handler to
1.61 + * get some free memory...
1.62 + */
1.63 + h_new = (std::new_handler)&foo;
1.64 +
1.65 + h_old = std::set_new_handler(h_new);
1.66 +
1.67 + try {
1.68 + /*
1.69 + * Try once more to see if our handler actually freed up some memory
1.70 + */
1.71 + bar();
1.72 + }catch(...){
1.73 + glob_val = 0;
1.74 + }
1.75 +
1.76 + CPP_TESTS_ASSERT_ALLWAYS(glob_val != 0);
1.77 +
1.78 + h_new = std::set_new_handler(h_old);
1.79 + return 0;
1.80 +}