Dynamic Memory
The variables we have been using up to this point have been statically allocated either in the data section of the executable program at compile time (global variables), or on the stack when a function is executed (local variables). Most programming languages also allow you to create dynamic variables allocated on the "heap" at run-time. Dynamic AllocationTo create or allocate a dynamic variable, you use the int x = 5; // static variable. int *p; // static variable. p = new int; // allocate a dynamic int variable. which allocates two static variables After a dynamic variable is created, it can be used just like any other variable, the only difference is that it must be indirectly accessed using the pointer to which it was assigned. We can initialize the newly created dynamic variable using the statement *p = 40; which produces Once the dyanmic variable has been initialized, it can then be used. The following statement uses the value in the dynamic variable pointed to by x = x + *p This statement modifies the value of The Garbage CollectionUnlike Java and Python, C++ does not provide garbage collection and thus does not automatically deallocate dynamic variables when you are finished with them. You are responsible for deallocating any dynamic variable you create when you no longer need it.
To delete a previously allocated dynamic variable, you use the delete p; p = NULL; When a dynamic variable is destroyed, the corresponding pointer variable is not modified. It is good practice, however, to set the pointer to NULL to prevent the accidental resuse later in your program.
Standard C Memory AllocationThe Allocation.
To allocate dynamic memory using the standard C approach, we call int *pInt = (int *) malloc( sizeof( int ) ); The
When the dynamic variable is allocated, Deallocation.
To deallocate dynamic memory previoulsy allocated with free( pInt ); pInt = NULL;
|