C++ Primer For Java Programmers Dynamic Memory<< Pointers | Table of Contents | Arrays >>
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 (:source lang=cpp:)*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. (:note warn:) Failure to deallocate dynamic memory can result in memory leaks which can lead to your program running out of memory. Be careful when allocating dynamic variables and make certain they are destroyed when no longer needed. (:noteend:) 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. (:note warn:)
Attempting to deallocate a static variable will result in a run-time error. Only variables dynamically allocated with 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;
|