-
November 14th, 2012, 01:02 PM
#1
Windows CE (STL + std::bad_alloc + CMemoryException, ...)
Hi,
I'm building an application for Windows CE and Windows Desktop. The cross compilation is possible using some preprocessor directive, a different VS project file and a different VS solution file.
As my application must be robust, I need to test each memory allocation and in the case of an memory allocation failure . I want to be able to correctly clean the previously allocated resources.
Here is an exemple to show you my actual problem :
Code:
#include <list>
using namespace std;
typedef struct _MyObject
{
int a[9999];
} MyObject;
int i = 0;
MyObject p;
list<MyObject> v;
try
{
// Force failure
for (; i < 999999; ++i)
{
v.push_back(p);
}
}
catch(CMemoryException* er)
{
DEBUG_ALERT("CMemoryException !");
}
catch(std::bad_alloc& er)
{
DEBUG_ALERT("bad_alloc error !");
}
And the following file (NewHandler.cpp) is only include on Windows CE (To force a std::bad_alloc) uppon a memory failure. As Windows CE malloc returns NULL instead of throwing std::bad_alloc exception.
Code:
// http://msdn.microsoft.com/en-us/magazine/cc164087.aspx
#include <new>
#include <new.h>
// 4073: initializers put in library initialization area
#pragma warning(disable: 4073)
#pragma init_seg(lib)
namespace
{
int new_handler(size_t)
{
throw std::bad_alloc();
return 0;
}
class NewHandler
{
public:
NewHandler()
{
m_old_new_handler = _set_new_handler(new_handler);
}
~NewHandler()
{
_set_new_handler(m_old_new_handler);
}
private:
_PNH m_old_new_handler;
} g_NewHandler;
}
On Windows Desktop the program allocate memory until a CMemoryException is thrown. This is the result I want also on Windows CE.
On Windows CE, the program allocate memory until the device show a popup message with the message "Memory system is very low". So I cannot intercept the moment when the first allocation failed ! Result, my program crash and the device too ! Not wise !.
Is there any way to circumvent this problem ?
I don't understand how can we catch memory problem on Windows CE, if we have NO WAY to detect it ? Take the list container as exemple, the push_back function returns nothing (void) and it doesn't throw any exeption when failing. So how can I more secure my code about allocation failure ?
Best regards,
Martin
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|