Tuesday, March 20, 2007

Be aware NULL point access violation!

A typical error message such like "Can't write in 0x00000000, access violated.", and mostly be seen with 0x00000000. It is meaningful, and often point to wrong coding habits.

It is very common to distinguish if a new was successfully deploy a memory for a pointer by its return value. As usual, new will return a pointer pointing to a allocated memory which is successfully initialized and ready to be used. If new failed to deploy the memory, it will return NULL back to the pointer. So it is reliable to code in such way :

if(!(ptr = new foo[n]))
ReportErrorAndTerminate("Fail of memory deploying!");

In fact, if we added if to EVERY new, everything will go all right -- except annoying coding style and full of padding code. In old style C, LongJmp/SetJmp had been used in this case. In modern C++, that is catch&try method.

try{
ptr = new foo[n];
ptr2 = new foo2[n];
...
...
}

catch(std::bad_alloc)
{
...
... //necessary process
...
}

catch(...)
{
...
...//catch unknown exceptions
...
}

That's the way how try and catch works. OK, lets recall the topic, why this error message occurs? It is because of bad coding habit and misunderstanding the process of full program. For example, if we forget add if over new :

ptr = new foo[n];

when new returns NULL(means fail to deploy memory), then any operation to the memory that ptr refers :

*ptr = foo("This thing!");

It will occur NULL pointer access violation, and pop-up an error message box with "0x00000000".

In fact, not only new but all pointer-associated operator will return NULL when operating encounters failure -- even most of coder will make this behavior as default. Use try and catch to avoid such case.