Skip to main content

Posts

Showing posts with the label delete operator

Dynamic Memory allocation in C++

Similar to C, C++ supports allocating memory at run time in the heap.  In C we use malloc (), calloc () and realloc () for this operation. And the memory thus allocated, is released using free ().  In C++ dynamic memory allocation uses two operators instead of functions, new and delete . Both these operators work on all basic data types as well as user defined classes and structures new operator new operator allocates memory to a variable and returns a pointer to it. new does not need number of bytes to be allocated, instead it needs data type of pointee. int * ptr = new int ; Here memory is allocated to an integer and its address is stored in ptr .  Value pointed by this pointer is not initialized. To initialize the pointee we can use the modified form int * ptr = new int ( 10 ); We have allocated memory for ptr and stored 10 in the location pointed by ptr. If new operator fails, it throws a bad_alloc exception. new[] operato...