Dynamic Memory Allocation in C++: Understanding Pointers and Dynamic Data Structures, Study notes of Computer Science

This chapter discusses the problem of not knowing the amount of variable space required at compile time and introduces dynamic memory as a solution. Dynamic memory is space allocated for variables at execution time using the operator 'new' in c++. The details of 'new', the heap, and how to access dynamic variables using pointers. Three examples are provided to illustrate dynamic memory allocation.

Typology: Study notes

Pre 2010

Uploaded on 08/18/2009

koofers-user-5d1
koofers-user-5d1 🇺🇸

10 documents

1 / 18

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CHAPTER 4 -- PART A
POINTERS AND DYNAMIC DATA
STRUCTURES
Problem: What if we don’t know ahead of time (at compile
time) the amount of variable space we will need?
If we under estimate an array size,
we’ll get a runtime error.
If we over estimate an array size,
we’ll have lots of unused memory.
Solution: Allow variables to be created at execution time.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download Dynamic Memory Allocation in C++: Understanding Pointers and Dynamic Data Structures and more Study notes Computer Science in PDF only on Docsity!

CHAPTER 4 -- PART A

POINTERS AND DYNAMIC DATA

STRUCTURES

Problem: What if we don’t know ahead of time (at compile time) the amount of variable space we will need? If we under estimate an array size, we’ll get a runtime error. If we over estimate an array size, we’ll have lots of unused memory. Solution: Allow variables to be created at execution time.

Dynamic Memory Defn: Dynamic memory is space that is allocated for variables at execution time. In C++, the operator new is used to create a variable dynamically. new does two things:

  1. Allocates space for a dynamic variable (and calls the associated constructor if it is an abstract data type)
  2. Returns the address (memory location) of the space it has allocated

Example 1 : Dynamic Memory Allocation typedef int* int_ptr; int_ptr Count; Count = new int; If the heap looks like this:

Example 2 : Dynamic Memory Allocation typedef int* RecPointer; A. RecPointer P1, P2, P3;

C. P3 = P1;

D. P1 = new int;

  • P
  • P
  • P
  • P
  • P