Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Dynamic Memory Allocation Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.

Similar presentations


Presentation on theme: "1 Dynamic Memory Allocation Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series."— Presentation transcript:

1 1 Dynamic Memory Allocation Ying Wu Electrical Engineering & Computer Science Northwestern University yingwu@ece.northwestern.edu EECS 230 Lectures Series

2 2 What to learn today? What motivate us to manage the memory dynamically? How to allocate memory dynamically?

3 3 Will it work? int main( ) { int size; cin >> size; int arr[size] for(int i=0;i<size;i++) arr[i] = i; return 0; } I know what you want to do. But this method won’t work. So, how can we do that? Keep it and we will see in this lectures!

4 4 Variable Name Database Task: to create a name database, in which each entry is a name of a variable, e.g., “var_1”, “a”, … If we have such a DB, we can search an entry given a name.

5 5 Arrays of Pointers Arrays can contain pointers –Commonly used to store an array of strings char *suit[ 4 ] = {"Hearts", "Diamonds", "Clubs", "Spades" }; –Each element of suit is a pointer to a char * (a string) –The strings are not in the array, only pointers to the strings are in the array –suit array has a fixed size, but strings can be of any size suit[3] suit[2] suit[1] suit[0]’H’’e’’a’’r’’t’’s’ ’\0’ ’D’’i’’a’’m’’o’’n’’d’’s’ ’\0’ ’C’’l’’u’’b’’s’ ’\0’ ’S’’p’’a’’d’’e’’s’ ’\0’

6 6 Name DB using Array of Ptrs bool Search(const char*, int&); char *g_nameDB[4]; void main() { g_nameDB[0] = “a”; g_nameDB[1] = “var_1”; g_nameDB[2] = “xyz”; g_nameDB[4] = “temp”; char query[100]; cin.getline(query,100); int ind; if(Search(query, ind)){ cout << “Found “ << g_nameDB[ind]); else cout << “was not found!” << endl; } bool Search(const char* q, int& index) { bool isFound = false; for(int k=0;k<4;k++){ if( !strcmp(g_nameDB[k], q)){ index = k; isFound = true; break; } return isFound; }

7 7 Question? In the previous example, the DB is fixed in the main function. However, we want to get it done in a more flexible way: –Allowing us to add an entry –Allowing us to delete a entry

8 8 Motivation for DMA When we declare an array, we have to specify the size; otherwise the compiler will never know how much memory it should allocate to this array. Therefore, we have to use e.g., int arr[100] It makes the code less flexible However, if we have no idea about the size of the array in advance, what can we do? Solution I: use a larger size, say 100000000 Solution II: my code can perform part of the memory management

9 9 The Idea We need some mechanisms that: –let my program decide memory usage –ask the O/S to allocate as much as memory as I want –O/S tells me where and how much the memory are –free the memory to O/S when I don’t need them

10 10 Implementation in C++ Dynamic Memory Allocation –new Creates an object of the proper size calls its constructor returns a pointer of the correct type –delete Destroys object frees space

11 11 Example: Allocate an object New int *ptr; ptr = new int; (*ptr) = 5; new creates an integer, returns pointer delete delete ptr; free the memory ptr 5 -57266

12 12 Allocate A Set of Object New a set double *ptr; int size = 10; ptr = new double [size]; new creates an double array, returns pointer to the array delete a set delete [] ptr; free the memory int num = 100; double *arr = new double [num]; … delete [] arr; num = 10; arr = new double [num]; … delete [] arr; Use your debugger to check what happens!!

13 13 // global variables to define the varDB #define MAX_SIZE_DB 100; char*gVarDB_Name[MAX_SIZE_DB]; // MAX_SIZE_DB is the maximum intgVarDB_Size; // the size of the DB doublegVarDB_Value[MAX_SIZE_DB]; // functions related to the varDB // Initialize the system variable DB void VarDB_Init() { // the first one is reserved for "ans" gVarDB_Size = 1; for(int i=0; i<MAX_SIZE_DB; i++){ gVarDB_Value[i] = 0.0; gVarDB_Name[i] = NULL; } VarDB_SetVarName(0,"ans"); } A sol. to the varDB

14 14 // set a name entry to the variable DB bool VarDB_SetVarName(const int& index, const char* name) { assert(index < gVarDB_Size); boolcode = true; if(gVarDB_Name[index]!=NULL){ if(strlen(gVarDB_Name[index])!=0) { delete [] gVarDB_Name[index]; } gVarDB_Name[index] = new char [strlen(name) + 1]; if(gVarDB_Name[index]){ strcpy(gVarDB_Name[index], name); } elsecode = false; return code; }

15 15 ATTENTON DMA is quite flexible and powerful But if not used carefully and correctly, it will be a disaster to your code –Memory leak! –A lesson The way to prevent turmoil –Pair new and delete –Know exactly new [] and delete [] –Know exactly what you want to do!

16 16 Questions for today 1.what is wrong and how to correct? char *string; string = new char [30]; free(string); 2.what is wrong and how to correct? double *pt; pt = new double [30]; delete double; 3.what is wrong and how to correct? int* myfunc(){ int arr[10]; for(int i=0;i<10;i++) arr[i] = 0; return arr; }

17 17 Question to think about Constructing a 2D array. A 2D array can be seen by a 2D pointer Will the following code work (to create a 3x4 matrix)? int **mat; for(int i=0;i<3;i++) mat[i] = new int [4]; How to delete this 2D array?


Download ppt "1 Dynamic Memory Allocation Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series."

Similar presentations


Ads by Google