Professional Documents
Culture Documents
21/10/2020
Today‘s lecture
▪ Pointers
▪ Referencing vs pointers
▪ Arrays & dynamic memory allocation
▪ Stack vs heap
▪ The new operator & memory leaks
▪ Concept of shalow/deep copying
▪ Void pointer
int *arr;
arr = new int[SIZE]; // allocation
int **arr2D;
arr2D = new int* [numRows]; // allocation
delete [] arr2D;
(individual elements can be accessed using indices!! (e.g., arr2D[0][2]=10;))
Stack:
▪ Special region of computer's memory that stores temporary
variables created by each function, including the main()
▪ Stack variables only exist in the block of code in which they
were declared (unless declared static)
▪ Advantages:
► Memory managed automatically
► CPU organizes stack memory therefore reading from and
writing to stack variables is very fast and efficient
▪ Disdvantages:
► Size limits (depending on the OS)
► Large chunks of memory, such as very large arrays, should
not be allocated on the stack to avoid overfilling the stack
memory (known as stack overflow)
M. Shahzad: Data Structures & Algorithms Lecture 3: Review C++ (Continued) 6
Stack vs Heap
Heap:
▪ Region of your computer's memory that is NOT managed
automatically
▪ Advantages:
► More free-floating region of memory i.e., only limited by the
size of virtual memory (i.e., RAM and swap space)
► May be accessed outside of the block in which it was
allocated
▪ Disadvantage:
► Needs to be explicitly freed by the program – Memory leaks
struct Node{
char *name; Output:
int age; => Wendy 20 Wendy 30
Node(char *n = “”, int a=0) {
name = strdup(n); The reason for this is that the
age = a; definition of Node does not
} provide a copy constructor
};
Node(const Node&);
Node node1(“Roger”, 20);
Node node2(node1); // node2 = node1;
The intention of these declarations is to create object node1, assign values to
the two data members in node1, and then create object node2 and initialize
its data members to the same values as in node1
strcpy(node2.name, “Wendy”);
node2.age = 30;
cout<<node1.name<<“ ”<<node1.age<<“ ”<<node2.name<<“ ”<<node2.age;
M. Shahzad: Data Structures & Algorithms Lecture 3: Review C++ (Continued)
Shallow / Deep Copy
► Linked lists