We discussed in the class that there are 3 major issues with pointers and dynamic memory allocations .
Identify the line numbers in the code snippet below for each issue listed above with one line explaining your reason.
A sample answer:
- Memory fault: line number 6: because a for-loop can't iterate more than 1,000,000
- Memory leak: line number 9; because ....
- Memory corruption: line number 7; because ....
[code snippet]
1. int *intPtr = new int; 2. int *intPtr2 = intPtr; 3. int *intPtr3 = x00FF1234; //Assume this is a valid address 3. *intPtr = 2123; 4. *intPtr2 = *intPtr = 11; 4. delete(intPtr) 5. (*intPtr2)++; 6. for (int i = 0; i <= 1000000; i++) { 7. int * intPtr = new int[1000]; 8. for (int j = 0; i <= 1000; j++) 9. intPtr[j] = *intPtr3++; 10. }
Memory leak is caused by programmers when they create a memory in heap and does not delete it.
The line 8 with for loop has an error as the checking condition is with respect to 'i' and not 'j'.
In line 9 memory is allocated for intPtr[j] but is not deleted afterwards which leads to memory leak. So add these 3 lines of code after the 9th line to overcome memory leak :
for (int j = 0; j<= 1000; j++)
delete Ptr[j];
delete Ptr;
The alteration of computer system memory without explicit assignment is known as memory corruption.
In line 7 an array is used in a loop, with wrong or incorrect terminating condition, so there is a chance of manipulating the memory beyond array bounds accidentally. When we use memory beyond memory that was allocated, it leads to memory corruption.
Get Answers For Free
Most questions answered within 1 hours.