Object-Oriented Programming Lecture 2: Pointer Variables and Dynamic Memory Management
Introduction and Course Information
- Course Title: Объект хандлагат программчлал (Object-Oriented Programming).
- Lecture Number: Лекц №2 (Lecture №2).
- Institution: МУИС, МТЭС (National University of Mongolia, School of Applied Sciences and Engineering).
- Department: Мэдээлэл Компьютерийн Ухааны Тэнхим (Department of Information and Computer Science).
- Lecturer: Д-р. Э. Авирмэд (Dr. E. Avirmed).
- Founding Date of Institution (Logo): 1942.
Classification of Variables
Variables in programming are classified based on how they are stored and their access scope. In this lecture, three primary types are discussed:
- Автомат (auto) хувьсагч (Automatic variables):
- Scope: Only accessible within the block or part of the program where they are declared (Заралсан хэсэг).
- Lifetime: They are automatically created in memory when the program enters their scope and are automatically destroyed when the program leaves that scope.
- Статик (static) хувьсагч (Static variables):
- Scope: Accessible within the section where they are declared (Заралсан хэсэг).
- Lifetime: These variables are created in memory as soon as the program starts running and persist until the program finishes execution.
- Хаяган (pointer) хувьсагч (Pointer variables):
- Scope: Accessible within the declared section (Заралсан хэсэг).
- Lifetime: Generally follow the rules of automatic variables. However, if the address they point to has been reserved using memory operators (like dynamic allocation), the memory remains allocated until it is explicitly released, regardless of the pointer variable's internal scope.
Memory Structure and Addresses
- Storage Location: Every variable is located in a memory cell (санах ойн үүр).
- The Cell (Үүр): A memory cell is composed of flip-flops that store 8 bits of information (1 byte).
- Addressing: Each cell has a specific identification number. This unique number assigned to a memory cell is called the Memory Address (санах ойн хаяг).
Pointer Variables and Basic Operations
- Definition: A variable that stores the memory address of another variable is called a pointer variable (хаяган хувьсагч).
- Static Declaration Example:
: This reserves 4 bytes of memory automatically for an integer variable.: The address of variableis assigned as the value to the pointer variable.
- Dynamic Allocation Example:
: This reserves 4 bytes of memory from the heap and assigns the starting address of this reserved memory to the pointer variable.: The value 12 is assigned to the reserved memory location by accessing it through the address stored in the pointer.: This command releases the reserved dynamic memory.
Pointer Function Example: testFunc
The following code demonstrates passing variables by reference using pointers to modify their values within a function:
- Code Structure:
- Function definition:
- Main execution:
followed by.
- Function definition:
- Execution Logic:
- Initial values:
. - Inside
, the value at the address ofis incremented, and the value at the address ofis multiplied by 10. - Output after function call:
.
- Initial values:
Limitations of C-style Arrays
The standard array implementation in the C language faces two significant drawbacks due to fixed memory allocation during compile time:
- Inefficiency and Overflow: If the fixed size of the array is significantly larger than the number of data entries, memory usage is inefficient. Conversely, if the size is smaller than the required data, a Buffer Overflow (хэт хэтрэлт) occurs.
- Compilation Constraints: These weaknesses exist because the size of a C array must be determined at the stage of converting the program into machine language (compilation).
- Temporary Solution: One can manually change a
constant and recompile the program every time the required size changes, but this is impractical. - Dynamic Solution: These issues are solved using dynamic memory mechanisms, which involve two main operations: reserving memory when needed and releasing it once used.
Memory Management Operators
C Language Operators
- Memory is reserved using the
family of functions. - Memory is released using the
function. - These require the header files
or.
C++ Language Operators
- While
andcan still be used in C++, the language introduces theandoperators. requires extra work such as explicit type casting and manually calculating the memory size required for the object, whereassimplifies this.
The new Operator
- Functionality: It reserves a portion of memory from the available free memory pool and returns the starting address of that section.
- Failure State: If there is insufficient memory to fulfill the request, it returns a null address or zero ().
- Syntax:
- Array Allocation: To prepare memory for an array of 50 real numbers (doubles), the command would be:
.
Anonymous Variables via new
- If a pointer variable (e.g.,
) is not null, the newly prepared memory serves as an anonymous variable (нэргүй хувьсагч) because the memory itself does not have a unique identifier name like a standard variable. - The return address (e.g.,
) becomes the value stored in the pointer variable. - Operations on Anonymous Variables:
: Storing user input into the dynamic memory.: Logical comparison and arithmetic operations.: Assigning a new value.
Dynamic Array Example with Safety Check
: Allocates memory for 10 integers.- User Input-based Allocation:
: Uses the assert function to verify that the memory was successfully allocated.: Filling the array with values.
The delete Operator
- Purpose: Once the memory is no longer needed, the
operator releases it and returns it to the free memory pool. - Relationship with
new:is a request to take from the pool;is a request to return and register the memory back to the pool. They are interdependent and complementary. - Syntax:
- For single variables:
- For arrays:
- For single variables:
- Dangling Pointers: After
is executed, the value of the pointerbecomes undefined but still holds the old address. Attempting to useagain will result in errors. - Safeguard: It is best practice to set the pointer to zero immediately after deleting:
.
Memory Leaks (Санах ойн цоорхой)
- Definition: A memory leak occurs when dynamic memory is allocated but never released, leading to orphaned memory segments that the program can no longer access but still technically owns.
- Mechanism of Failure:
- First Iteration: A pointer (e.g.,
) is used to allocate an array of 10 integers. - Subsequent Iterations: If new memory is allocated to the same
without first usingon the previous address, the first array's memory remains registered to the program but has no pointer directing to it. - Result: Repeated iterations will eventually exhaust the available memory until the condition
fails and the program terminates.
- First Iteration: A pointer (e.g.,
- Prevention Example (Do-While Loop):
cpp do { int *intPtr = new int[10]; assert (intPtr != 0); // ... program logic ... delete[] intPtr; // Proper release of memory intPtr = 0; // Clearing the pointer (good habit) cout << "\n Do another (Y or n)?"; cin >> answer; } while (answer != '\n');