Memory Management (Garbage Collection and Pointers) - EduardoMSU/OOP-2143 GitHub Wiki

Memory Management (Garbage Collection and Pointers in Object-Oriented Programming (OOP)

What is Memory Management?

Memory management refers to the process of allocating, using, and freeing memory in a program. In object-oriented programming (OOP), memory management involves controlling how objects are created, used, and destroyed during the lifetime of a program. It ensures that memory is efficiently utilized and that resources are freed when no longer needed.


Key Concepts in Memory Management

Concept Description
Heap Memory Dynamic memory allocated at runtime, usually for objects or data whose size isn't known at compile time.
Stack Memory Memory used for storing function calls, local variables, and object instances with a known size.
Garbage Collection Automatic memory management used in languages like Java or C# to reclaim memory that is no longer in use.
Manual Memory Management In languages like C++ where developers are responsible for explicitly allocating and deallocating memory.
Memory Leaks Occur when memory is allocated but not properly freed, leading to inefficient memory use and potential crashes.

Types of Memory Allocation

Type Description
Static Memory Allocation Memory is allocated during the program's compile-time, and it remains fixed throughout the program's execution.
Dynamic Memory Allocation Memory is allocated at runtime, often through the new or malloc() functions, and must be manually freed using delete or free().

Memory Management in C++ (Manual Memory Management)

In C++, memory management is typically manual. The programmer needs to allocate and deallocate memory as necessary using the new and delete operators.

Example of Manual Memory Management

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;

    // Constructor to initialize instance variables
    Student(string n, int a) {
        name = n;
        age = a;
    }

    // Method to display student details
    void displayDetails() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // Dynamically allocate memory for an object
    Student* studentPtr = new Student("Alice", 20);

    // Accessing members using the pointer
    studentPtr->displayDetails();  // Name: Alice, Age: 20

    // Manually deallocate memory when no longer needed
    delete studentPtr;

    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️