Courses / HEC NSCT – National Skill Competency Test: Complete Preparation for Computing Graduates
2.4 Memory Management and Exception Handling
Area 2 – Programming (C++ / Java / Python) (10%) · 45 min read · 12 MCQs to check yourself
Stack vs heap
| Stack | Heap |
|---|---|
| Local variables and function calls | Dynamically created objects (new) |
| Freed automatically when the function returns | C++: freed manually with delete; Java/Python: garbage collector |
| Small, fast | Larger, slower to manage |
Pointers and references (C++)
int *p = &x; – p stores the address of x; *p gives the value. nullptr = pointer to nothing.
Common bugs: memory leak (forgot delete), dangling pointer (using memory after it is freed), double free, null-pointer dereference. Modern C++ uses smart pointers (unique_ptr, shared_ptr) and RAII to free memory automatically.
Java has references but no pointer arithmetic; Python variables are names bound to objects (reference counting + garbage collection).
Exceptions
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Always runs");
}
finallyruns whether or not an exception occurred (used to close files/connections).- Java checked exceptions (e.g.
IOException) must be caught or declared withthrows; unchecked exceptions (NullPointerException,ArithmeticException) need not be. - Python:
try / except / else / finally;raisethrows an exception.
Stack vs heap memory – simple explanation (Alex Hyett)
This lesson ends with a quiz of 12 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: 2.3 Object-Oriented Programming · Next: 2.5 Code Tracing, Debugging and Good Practice