0% found this document useful (0 votes)
6 views29 pages

lec16-dyn_mem

Uploaded by

Mamat Rahmat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views29 pages

lec16-dyn_mem

Uploaded by

Mamat Rahmat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

CSCI1540

Fundamental Computing
with C++
Dynamic Memory Management

Fall, 2024
Outline
• Dynamic Memory Management
• Allocation
• Deallocation

• Dynamic Memory Management and Arrays


• 1-D array
• 2-D array

• Dynamic Memory Management and Objects


• Destructors

2
Dynamic Memory Management
• Manage memory usage at runtime

• While you program is running, you can explicitly

• Allocate (or reserve) memory space to store data

• Release (or free up) the previously allocated memory


space

• You cannot just store/access data anywhere you


want in the memory

3
Memory Allocation: Operator new
int *p; p ?

• p is a pointer variable
• It is automatically allocated a memory space for
storing an address

4
Memory Allocation: Operator new
int *p; p ? ?
p = new int;

• Operator new reserves a memory space that is big


enough to store a value of type int
• Typically 32 bits for int

5
Memory Allocation: Operator new
int *p; p ? ?
p = new int;

• Operator new returns the address of the reserved


space and the address is assigned to p
• Pointer assignment

• Allocated space will still remain reserved until


explicitly released (later) or the program terminates

6
Memory Allocation: Operator new
int *p; p 10
?
p = new int;
*p = 10;

• Store 10 in the allocated space targeted by pointer


p
• The allocated space is “like an int variable”, except
that it has no name

7
Losing Allocated Space Bye bye!

int *p; p 10
p = new int;
*p = 10;
p = new int; ?
• The allocated space has no corresponding name in the
program

• If you lose the memory address of an allocated space,


you lose access to the data stored in that space

• Allocated space will stay reserved until explicitly


released (see later) or program terminates
8
Memory Allocation: Operator new
• Operator new is for allocating memory space to
store data
• It reserves a continuous chunk of memory space that is
big enough to store a particular type of data
• Upon successful allocation, it returns the memory
address of the allocated space
• You should always use a pointer variable to save the
memory address returned by new
• Unless the reserved space is explicitly freed (released), it
cannot be reallocated

9
Memory Deallocation: Operator
delete
• For freeing up the previously allocated memory
space
• E.g.: int *p;
p = new int;
… p 10
delete p;

• Free up (release) the memory space pointed to by p


• The space to be freed must be a space previously
allocated using the new operator
• delete knows how many bytes to free
Always manually release dynamically
allocated memory that is no longer needed 10
Operator delete: Example
1 int *p1, *p2;
2
3 /* Allocate a space to store an integer.
4 Initial value is undefined */
5 p1 = new int; // Call this space #1
6
7 /* Allocate a space to store an integer, and initialize its
8 value to 10 */
9 p2 = new int(10); // Call this space #2
10
11
12
13
14 p1 ?
15 p2 10
16
17
18
19 11
Operator delete: Example
1 int *p1, *p2;
2
3 /* Allocate a space to store an integer.
4 Initial value is undefined */
5 p1 = new int; // Call this space #1
6
7 /* Allocate a space to store an integer, and initialize its
8 value to 10 */
9 p2 = new int(10); // Call this space #2
10
11 // Free the space pointed to by p1
12 delete p1; // Release space #1
13
14 p1 ?
15 p2 10
16
17
18
19 12
Operator delete: Example
1 int *p1, *p2;
2
3 /* Allocate a space to store an integer.
4 Initial value is undefined */
5 p1 = new int; // Call this space #1
6
7 /* Allocate a space to store an integer, and initialize its
8 value to 10 */
9 p2 = new int(10); // Call this space #2
10
11 // Free the space pointed to by p1
12 delete p1; // Release space #1
13
14 // Both p1, p2 point to space #2 p1 ?
15 p1 = p2; p2 10
16
17
18
19 13
Operator delete: Example
1 int *p1, *p2;
2
3 /* Allocate a space to store an integer.
4 Initial value is undefined */
5 p1 = new int; // Call this space #1
6
7 /* Allocate a space to store an integer, and initialize its
8 value to 10 */
9 p2 = new int(10); // Call this space #2
10
11 // Free the space targeted by p1
12 delete p1; // Release space #1
13
14 // Both p1, p2 point to space #2 p1 ?
15 p1 = p2; p2 10
16
17 /* It is possible to free a space through another pointer
18 variable. Free the space targeted by p1 */
19 delete p1; // Release space #2 14
Pitfalls in Using delete
1 int x, *ptr;
2 Cannot release a space that is
3 ptr = &x; not dynamically allocated by new
4 delete ptr; // Runtime error

1 int *ptr; Runtime error is ptr is not NULL.


2
3 ptr = …; // not "new"
Cannot release a space that is not
4 delete ptr; // Runtime error dynamically allocated by new

1 int *ptr;
2 … delete will do nothing
3 ptr = NULL; if pointer is NULL
4 delete ptr; // Safe, but redundant 15
Pitfalls in Using delete
1 int *ptr = new int; Dangerous to use a released space
2
3 delete ptr;
because it can be reallocated to
4 *ptr = 10; // Runtime error somebody else already

1 int *ptr = new int;


2 … Cannot release an
3 delete ptr; already released space
4 delete ptr; // Runtime error

16
Using new and delete with 1-D
Arrays
1 int *a, i, n;
2 cin >> n; // Let's say, enter 100000000
3 a = new int[n];
4 // a is pointing to an array of 100,000,000 int's (~381MB)
5
6 for (i = 0; i < n; i++) A dynamically allocated
7 a[i] = …; array whose size is
8 … determined at runtime
9 // Free up ALL the space occupied by a
10 delete [] a;

(before new) (between new (after delete)


and delete) 17
Enlarging a Dynamically Allocated 1-D
Array: Example
1 int *foo, n;
2 cin >> n;
3 foo = new int[n];
4
5 … // Suppose foo[0…n-1] are assigned some values here
6
7 /* Suppose now we want to enlarge foo to hold 2n integers,
8 and retain the existing data.
9 Solution: (1) Allocate a larger array;
10 (2) Copy the data from foo to the new array;
11 (3) Free up the space occupied by foo; and
12 (4) Make foo point to the new array space
13 */
14 int *tmp = new int[2 * n]; // (1)
15 for (int i = 0; i < n; i++) // (2)
16 tmp[i] = foo[i];
17 delete [] foo; // (3)
18 foo = tmp; // (4) 18
(Optional)

Dynamic 2-D Array: Allocation


1 /* Can also be interpreted as pointing to an array of
2 "pointers to int" */
3 int **foo;
4 int row = 10;
5
6 // foo stores the base address of this array
7 foo = new int *[row]; // Each element is an int-pointer

foo
?
?
foo[1]
?
⋮ 19
(Optional)
Dynamic 2-D Array: Allocation
1 int **foo;
2 int row = 10, col = 4, i, j;
3
4 foo = new int *[row]; // Each element is an int-pointer
5
6 // Allocate a 1-D array for each row
7 for (i = 0; i < row; i++)
8 foo[i] = new int[col];
9 // Now foo can be used as a row-by-col 2-D array of int
10 for (i = 0; i < row; i++)
11 for (j = 0; j < col; j++)
12 foo[i][j] = …;
foo[1][2]
foo
? ? ? ? ?
?
foo[1] ? ? ? ?
?
⋮ ? ? ? ? 20
(Optional)
Dynamic 2-D Array: Deallocation
1 int **foo;
2 int row = 10, col = 4, i, j;
3
4 foo = new int *[row]; // Each element is an int-pointer
5 // Allocate a 1-D array for each row
6 for (i = 0; i < row; i++)
7 foo[i] = new int[col];
8 …
9 // Free the space of each row first
10 for (i = 0; i < row; i++)
11 delete [] foo[i];
12 delete [] foo; // Finally, free the array of pointers

foo
? ? ? ?
? ? ? ?

⋮ ? ? ? ? 21
(Optional)

Dynamic 2-D Array:


Allocation/Deallocation (Alternative)
1 int **foo, *tmp;
2 int row = 10, col = 4, i;
3
4 // Allocate space for an array of pointers
5 foo = new int *[row];
6
7 /* Alternative approach:
8 Allocate a 1-D array big enough for all elements in the
9 2-D array and then share the space among all rows */
10 tmp = new int[row * col];
11 for (i = 0; i < row; i++)
12 foo[i] = &tmp[col * i];
13
14 …
15 delete [] tmp;
16 delete [] foo; 22
(Optional)

Dynamic 2-D Array:


Allocation/Deallocation (Alternative)
0 1 2 3 4 5 6 7 8 … 36 37 38 39
? ? ? ? ? ? ? ? ? ? ? ? ? ?
tmp

foo foo[1][2]
0
1
2
⋮ ⋮
9 int **foo, *tmp;
foo = new int *[row];
Allocate a 1-D array (tmp) big enough tmp = new int[row * col];
for all elements in the 2-D array and for (i = 0; i < row; i++)
then share the space among all rows foo[i] = &tmp[col * i];23
(Optional)

Using new with Classes and


Objects
class Date { datePtr
public:
Date(); // Constructor #1
Date(int,int,int); // Constructor #2 … d
… … m
private: … y
int y, m, d;
};
Date *datePtr;

// Use default constructor (#1)


datePtr = new Date; • The dynamically allocated
// Or: new Date(); space stores an object

// Use the Constructor #2
• A constructor of the object
datePtr = new Date(2046, 12, 25); is called automatically 24
(Optional)

Using delete with Objects


Date datePtr = new Date(2046, 1, 1);

datePtr->setMonth(12);
datePtr->setDay(25);

delete datePtr; // Calls destructor implicitly

• Releases the space occupied by the object


datePtr • Automatically invokes the destructor of
the object (if there is one)
25 d
12 m
2046 y
25
(Optional)

Destructor
class GradeBook { GradeBook.h
public:

~GradeBook(); // Destructor
private:
string courseName;
int n;
int *grades; // Dynamically allocated array
};
• Destructor name: “~” + class name
• No return type; no parameters
• At most one destructor per class
• Used for “clean up” purpose
• E.g., for freeing dynamically allocated data members 26
(Optional)

Destructor
… GradeBook.cpp
// Constructor
GradeBook::GradeBook(…) {
A GradeBook object contains
grades = new int[n];
… a dynamically allocated array
} data member grades

// Destructor
GradeBook::~GradeBook() {
delete [] grades;
} Need to free the allocated space
of the array in the destructor

27
(Optional)

Destructor
… GradeBook.cpp
int main() {

GradeBook *book = new GradeBook(…);


book->processGrades();

delete book; // Calls destructor implicitly


return 0;
}
• Programmers cannot call destructors explicitly
• It is called automatically when an object is being
“deleted”
28
Summary
• Dynamic memory allocation (new)
• Dynamic memory de-allocation (delete)

• Dynamic memory for creating/releasing 1-D arrays

• Dynamic memory for 2-D arrays (Optional)

• Dynamic memory for objects (Optional)


• Destructors (Optional)

29

You might also like