Thursday, February 16, 2006

testing memory failure allocation

there is a difference of how the memorey failure is handled in C++.
int *pa = new int[10000];

in the article "The new and delete Operators" the MSDN says:
"Beginning in Visual C++ .NET 2002, the CRT's new function (in libc.lib, libcd.lib, libcmt.lib, libcmtd.lib, msvcrt.lib, and msvcrtd.lib) will continue to return NULL if memory allocation fails. However, the new function in the Standard C++ Library (in libcp.lib, libcpd.lib, libcpmt.lib, libcpmtd.lib, msvcprt.lib, and msvcprtd.lib) will support the behavior specified in the C++ standard, which is to throw a std::bad_alloc exception if the memory allocation fails."

hence is vital to know which one you are using.
"Normally, if you #include one of the C++ standard headers, like , you'll get a /defaultlib directive in your object that will reference the appropriate C++ Standard Library according to the CRT model you used (the /M* compiler options). Generally, that will cause the linker to use the throwing operator new from the C++ Standard Library instead of the nonthrowing one from the main CRT, because the order of defaultlib directives will cause libcp.lib to be searched before libc.lib (under /ML)."

hence if you have the following code:

int *pn = new int[1000];

// ok, pn is valid

the testing is valid only if you use the CRT new and not when you use the std::new. with the std::new this is not valid, it will throw an exception (i am not sure what will pn point to).

No comments: