Uninitialized pointer variables
If you do not store something into a pointer variable,
then it contains a junk value. The computer does not
guess what you want it to point to. |
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 makes pd point to newly allocated memory big enough for a value of type double. |
Deallocating memory in the heap
If pointer p was obtained as the value of an expression of the form
new T, then statement
delete p;deallocates the memory pointed to by p. (It does not destroy variable p itself. It affects the memory pointed to by p.) Really, delete 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 corrupt the heap manager. Chaos to ensues. Really. |
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