New Allocation in C
In C , when the new operator fails to allocate memory, it raises a std::bad_alloc exception. However, certain compilers, such as VC6, reportedly deviate from this standard.
VC6 Behavior
VC6 does not adhere to the C standard and instead returns 0 (or NULL) when memory allocation fails. This non-conformity can lead to code that looks untidy due to the constant need to check for NULL after each new statement.
Resolution
Microsoft acknowledges this issue in Knowledge Base Article KB276944. To work around it in VC6, MSVC allows linking with a custom new handler. In newer MSVC compilers (7.0 and above), linking with the nothrownew.obj object file provides the same behavior as VC6.
VS2005 and Beyond
MSVC 8.0 (VS2005) introduced a change where new now consistently raises std::bad_alloc by default. The option to return 0 can still be specified using the std::nothrow parameter, as shown in the code example provided. This is a backwards-compatible solution that allows code to work with any compiler version.
The above is the detailed content of How Does Memory Allocation in C Differ in VC6 Compared to Newer Compilers?. For more information, please follow other related articles on the PHP Chinese website!