Memory Management

Memory Management - Lecture 5a Memory Management Categories...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
Lecture 5a Memory Management
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Categories of Memory Code Area For storing machine instruction Static Data All global variables Static data (static data local to a function or static class data members) Run-time Stack Local or non-static variables Heap Dynamic allocated memory (using new for allocation.)
Background image of page 2
Heap Memory Dynamic Memory Allocation Employee *boss = new Employee(…); //pointer boss is allocated on stack, while the object //pointed by boss is allocated on heap. double* data = new double[10]; new operator Deleting Dynamically Allocated Storage delete boss; //free the object delete[] data; //free the whole array delete operator
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Common Memory Errors Using a value that has not been initialized Using a pointer to reference a location that is no longer valid Forgetting to delete a dynamically allocated section of memory Deleting a memory value that was never allocated Deleting a dynamically allocated section of memory more than once
Background image of page 4
Initialization Errors Ex 1: int nickels; int dimes = 3; double total = nickels * 0.05+dimes*0.10; //unpredictable result Ex 2: Employee *boss; cout << “My boss earns “ << boss->salary(); //error! Pointer is undefined. //Program will crash.
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Lifetime Errors After a function returns, all local variables no longer valid Ex1: int* read_an_array() { int buffer[10]; for (int j=0; j<10; j++) cin >> buffer[j]; return buffer; } //error: return pointer to a local variable int *p = read_an_array(); //array does not exist Ex2: Fraction result (….); return result; } //error: return reference to a local variable
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 20

Memory Management - Lecture 5a Memory Management Categories...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online