Docsity

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

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