160k views
4 votes
Write a function that dynamically allocates a block of memory and returns a char pointer to the block. The function should take an integer argument that is the amount of memory to be allocated. If the new operator cannot allocate the memory, the function should return a null pointer.

1 Answer

5 votes

Answer:

#include<new>

using std: :bad_alloc;

char* function ( int size )

{

try

{

char *p = new char [ size ] ;

return p ;

}

catch ( bad_alloc )

{

return NULL;

}

} // end function

User Zorgarath
by
3.9k points