Allocating memory in the heap
To allocate memory for
a variable of type T, use expression
new T.
It allocates the required memory and returns its
address (a pointer if type T*). For example,
int* pi = new int; double* pd = new double;makes variable pi point to a newly allocate chunk of memory big enough to hold one int and pd point to newly allocated memory big enough for a value of type double. |
Deallocating memory in the heap
If pointer p was given to you by an expression of the form
new T, then statement
delete p;deallocates the memory pointed to by p. (It does not destroy p itself.) Really, it just recycles the memory. The heap manager takes ownership of the memory, and it might give that same memory back to you at a future use of new. Important note. Only delete a pointer that was given to you by new. Never try to delete a local variable of a function. Doing that will cause chaos to ensue. |
Allocating memory in C (optional)
Although we are using C++, it is worth mentioning that the
new operator is not part of C. To allocate memory in
the heap in a C program, you use a more primitive mechanism: a call
to a function called malloc, which takes one argument, the number
of bytes to allocate, and returns a pointer of type
void*
to a newly allocated chunk of that many bytes. Statements
int* p = (int*) malloc(sizeof(int)); double* q = (double*) malloc(sizeof(double));are similar to the statements above that allocate using new. For any type T, sizeof(T) is the number of bytes that a variable of type T needs. |
Deallocating memory in C (optional)
If p is a pointer that was given to you using malloc, then
statement
free(p);gives the memory pointed to by p back to the heap manager. Malloc and free are not necessarily compatible with new and delete. Allocating using new and then deallocating using free can cause chaos to reign. |
Only deallocate memory when you are truly finished with that memory. If you have more than one pointer to a chunk of memory, then deallocating that chunk makes all pointers to it stale; they are pointing to memory that you are no longer allowed to use. Those pointers are called dangling pointers. |
Watch out: no automatic deallocation in the heap
Write a statement that creates variable p of type long* and makes p point to newly allocated memory of type long. Use the C++ method of allocating memory. Answer
Suppose that the memory pointed to by p from the preceding question is no longer needed. Write a statement that deallocates that memory. Answer
What is a memory leak? Answer
What are the consequences of a memory leak? Answer
What is a dangling pointer? Answer
Is the following function a suitable substitute for the new operator for allocating new memory to hold one int?
int* newInt() { int n; return &n; }That is, can you use
int* p = newInt();instead of
int* p = new int;Answer