Download presentation
Presentation is loading. Please wait.
1
Dynamic Memory Allocation in C++
2
Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds global data – Stack Segment Used to contain local variable and other temporary information In addition to these, the operating system provides and extra amount of memory called Heap
3
C++ Variable Name – An identifier to recognize the variable Type – The set of values it can take Scope – The area of code it is visible to Address – The address at which the variable is located Size – The amount of memory to store its content
4
An Example Void cookie() { int integer_x; ……. } Name: integer_x Type: int Scope: local, only visible within the cookie function Size: 32 bits (can vary)
5
Dynamic Variable Stored in heap, outside the stack and data segments May change size during runtime or may disappear for good If no explicit allocation of memory is done, it never exists double *dp; – Tells the compiler to have a pointer dp that will hold the starting address of a variable of type double in heap memory
6
Dynamic Variable (contd…) To create the dynamic variable new is used. – dp = new double; Will create a dynamic variable of type double and makes dp pointer point to its starting address It is always a good practice to initialize dynamic variables. – *dp = a or dp = new double(a);
7
Visual Demonstration dp 0045:02FE ….. …… 0045:02FE ….. …. ….. …… ……. 3.1415 ….. ……. *dp Pointer variable (data segment) Dynamic Variable (Heap)
8
Deleting Dynamic Variable delete operator is used to delete the memory allocated for the dynamic variable in heap delete dp; – Will delete 8 bytes of the memory allocated for the double variable NOTE: the dp pointer will not be erased as it is created in code/data segment and can be point some other dynamically allocated memory location
9
Dynamic Arrays C++ also provides the possibility to allocate an entire array in the heap – int *table; – table = new int[100]; Assigns 100 * sizeof(int) = 100 * 4 = 400 bytes of memory and assign the starting address to table pointer Arrays defined in heap are similar to the ones defined in data and code segments and can be accessed using [] For (int i = 0; i < 100; i++) – table[i] = 0; will initialize all the array items to zero
10
Deleting Dynamic Arrays Again delete operator is used – [] is used will delete operator to tell the compiler that you are deleting arrays not variables delete [] table; will delete not only the memory location pointed by table but all the items in the array
11
Common mistakes made in dynamic allocation Freeing an already freed variable char *str = new char [100]; delete [] str; delete [] str; // error Freeing a dynamic variable not assigned yet char *str; delete str; // error Accessing or assigning value to the freed variable int *str = new int[100]; delete [] str; str[10] = 90; // error
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.