Showing posts with label new. Show all posts
Showing posts with label new. Show all posts

Wednesday, 13 September 2017

Allocating Void pointer memory using new operator

I was Implementing Generic List in C++ and was able to successfully allocate memory of void*  data using malloc ( malloc return void *) . But how about using new. Can we do below


void Test()
{
           void *f= new void[25];  //void *f=malloc(25); --> Works
           delete f;
}


The Answer is NO.
Because void has no size . How much space has to be allocated is not known.

So if you need to allocate memory using new use operator like


void Test()
{
          void *f=operator new(25);
          delete f;
}





Monday, 14 July 2014

new and delete



  1.  Syntax: void*  operator new(size_t size);
      Three forms of using new
    • T* p = new T
    • T* p = new T(value)
    • T* p = new T[size]                                                                
  2. new is an operator to Allocate memory for an object or array of objects of type-name from the free store and returns a suitably typed, nonzero pointer to the object.The pointer returned is cast to the data type implicitly
  3. When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.Invokes default constructor on all the objects in case of an array of objects
  4. If unsuccessful, new returns zero or throws an exception.You can change this default behavior by writing a custom exception-handling routine and calling the  _set_new_handler run-time library function with your function name as its argument.
  5. To allocate and then frees a two-dimensional array of characters of size w by 10.                                            char (*pchar)[10] = new char[dim][10];                                                                                        delete [] pchar;
  6. The type-name cannot contain const, volatile, class declarations, or enumeration declarations. Therefore, the following expression is illegal.
  7. The new operator does not allocate reference types because they are not objects.
  8. The new operator cannot be used to allocate a function, but it can be used to allocate pointers to functions. The following example allocates and then frees an array of seven pointers to functions that return integers.                                                                                                            int (**p) () = new (int (*[7]) ());                                                                                            delete *p;