TheUnknown
TheUnknown

Reputation: 66

do we need to create an pointer validation for gcnew

1) Do we need to have a pointer validation for following code in cli. Is it good to have?

NameClass NameString^ = gcnew NameClass();

if (NameClass)
{
   // some process

2) If we created a memory in one function and passing as pointer to other do we need to have validation ?

foo()
{
  try {
         NameClass *pNameString = new NameClass();
         foo_2(pNameString);
      } catch(std::bad_alloc &error)
         {
            std::cout << error.what() << std::endl;
         }
}

foo_2(NameClass *pNameString)
{
   if (pNameString)  // do we need to validate here ?
   {
     // some stuff
   }
}

3) Do we need to validate locally created object in reference passing ?

NameClass objNameClass;
foo(&objNameClass);

foo(NameClass *objNameClass)
{
  if (objNameClass) // do we need to validate here ?
  {

Upvotes: 0

Views: 206

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

It's just as unnecessary just after a gcnew as it is after a new. It's only necessary if you use C allocators like malloc for some reason. The C++ and C++/CLI constructs use exceptions for unsuccessful object creations, unlike the C functions which return a null pointer.

In plain C++, new will throw std::bad_alloc if memory cannot be allocated. In C++/CLI, gcnew will throw System::OutOfMemoryException in that case.

Is most cases, you probably should let the exception propagate and kill your program, because it's probably doomed anyway.


In your second example, you may want to validate the pointer in foo_2 only if you expect someone to call foo_2 with a null pointer, and when that is a valid usage. If it's invalid usage to pass it a null pointer as an argument, then you have a bug and should probably let your application crash (instead of letting it corrupt your data for instance). If foo_2 is only visible to the code which calls it immediately after allocation, it's unnecessary as it won't ever be null.

Same for the third example. The contract/documentation of your function should specify whether it is valid to call it with a null pointer, and how it behaves.

And please, don't ever write that:

catch(std::bad_alloc &error)
{
    std::cout << error.what() << std::endl;
}

If you have a low memory condition on a regular object allocation, just let your program die. Trying to cure it that way won't get you very far.

The only place when such code would be acceptable IMHO is when you're trying to allocate a potentially big array dynamically, and you know you can just cancel that operation if you're unable to do so. Don't attempt to catch allocation errors for every allocation, that will bloat your code and lead you nowhere.

Upvotes: 1

Related Questions