Stubbing Operator New in Environment

Question:
I would like to use the new operator in order to test an exception in my code. How do I force the 'new' operator to be stubbed in VectorCAST?
Answer:

There is a way to force operator new to be stubbed. It involves pre-declaring it in unit prefix user code (Environment | User Code | Edit). However, it is probably easier to simply define it yourself, and have it fail whenever a particular condition is met (which you can control). For instance, try this:
 

  • add the following code to User Globals User Code:

VCAST_USER_GLOBALS_EXTERN int num_calls_to_new;
VCAST_USER_GLOBALS_EXTERN int new_fails_on_call;

 

  • add the following code to Environment User Code - Data:
     

  #include <stdlib.h>
  #include <new>
  extern int num_calls_to_new;
  extern int new_fails_on_call;


  void *operator new(size_t sz, const std::nothrow_t&) throw ()
  {
    if ( ++num_calls_to_new == new_fails_on_call )
    {
      return 0;
    }
    return malloc(sz);
  }


  void *operator new[](size_t sz, const std::nothrow_t&) throw ()
  {
    if ( ++num_calls_to_new == new_fails_on_call )
    {
      return 0;
    }
    return malloc(sz);
  }


  void *operator new(size_t sz) throw (std::bad_alloc)
  {
    if ( ++num_calls_to_new == new_fails_on_call )
    {
      throw std::bad_alloc();
    }
    return malloc(sz);
  }


  void *operator new[](size_t sz) throw (std::bad_alloc)
  {
    if ( ++num_calls_to_new == new_fails_on_call )
    {
      throw std::bad_alloc();
    }
    return malloc(sz);
  }


  void operator delete(void* ptr) throw ()
  {
    if ( ptr )
      free(ptr);
  }


  void operator delete[](void* ptr) throw ()
  {
    if ( ptr )
      free(ptr);
  }

 

  • save the changes
  • rebuild your environment
  • in your test case, you will now be able to set new_fails_on_call to the Nth call to new which you want to fail. For instance, if the call to new which you want to fail is the 3rd call, you would set new_fails_on_call to 3 in the parameter tree.

Keep in mind that the VectorCAST-generated code may call new before your function is called or when stubs are called, or your function may call your own functions which call new. So the number of calls to new may not be obvious. In the parameter tree you can set the expected value for num_calls_to_new to <<ANY>> to have VectorCAST show its value in the report, which would help you determine how many hidden calls you need to account for.
 



Article ID: 1506
Last updated: 2019-11-11
Revision: 4
VectorCAST -> C++ Unit Testing -> Stubbing Operator New in Environment
https://kb.vector.com/entry/1506/