CSC 230 - Lecture 03-Memory

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

1

CSC230

Memory Management
Von Neumann Architecture
2

John Von Neumann, 1945


Why memory is a big deal?
3

• Both instructions (code) and data are stored inside memory


• Memory size is limited
• When you need some data, which should be inside the memory
• When you do not need the data, reassign the memory
• Data must be accessed in an efficient way (a major topic of this course)
How a program views memory
4

• Memory locations have address 0


• Text segment Code
Code is located at low addresses
• Global variables are located after code …
• System stack: memory for each function call Data segment Globals
• Parameters, local variables …
• Return address (where to return)
• etc. Heap
• Usually, NO CODE on the stack
• Heap: Memory can be allocated and de-allocated during
program execution (dynamically at run-time) based on the
needs of the program. …
• Heap grows downward, stack grows upward
• If your program uses up memory, heap and stack
collide, program aborts. … Stack
(area for
data local to
fffffffc a function)

Memory
Variables and static allocation
5

Each variable/object in a computer has a: Code Computer


• Name (such x, used by programmer)
• Address (used by computer to reference int x; x
it) string s("tcnj"); 0x3a0 -15
• Value s
• Scope (the lifetime and visibility to other 0x3a4 4
code) "tcnj"

Automatic/local scope main


• {…} of a function, loop, or if int main() x
{ 0x3a0 -15
• Stored on the stack int x;
• Dies/deallocated when ‘}’ is reached if( x ){ if
String
s
s("tcn
j"); 0x3a4 4
} "tcnj"

Here we use container box to represent scope }


Local variables
6

Variables declared inside function or block, {…},


are stored on the stack
// Computes rectangle area,
Stack // prints it, & returns
it int area(int, int);
void print(int);
int main()
{
int wid = 8, len = 5, a;

a = area(wid,len);
}
int area(int w, int l)
{
int ans = w * l;
print(ans);
return ans;
}

void print(int
area)
{
cout << “Area is
“ << area;
Local variables
7

Variables declared inside function or block, {…},


are stored on the stack
// Computes rectangle area,
Stack // prints it, & returns
it int area(int, int);
void print(int);
int main()
{
int wid = 8, len = 5, a;

a = area(wid,len);
}
int area(int w, int l)
{
int ans = w * l;
print(ans);
return ans;
}
0xbf0 wid
0xbf4 void print(int
main len
area)
0xbf8 a {
00400120 Return
cout << “Area is
0xbfc link “ << area;
Local variables
8

Variables declared inside function or block, {…},


are stored on the stack
// Computes rectangle area,
Stack // prints it, & returns
it int area(int, int);
void print(int);
int main()
{
int wid = 8, len = 5, a;

a = area(wid,len);
}
int area(int w, int l)
{
int ans = w * l;
print(ans);
return ans;
}
0xbf0 8 wid
0xbf4 5 void print(int
main len
area)
0xbf8 a {
00400120 Return
cout << “Area is
0xbfc link “ << area;
Local variables
9

Variables declared inside function or block, {…},


are stored on the stack
// Computes rectangle area,
Stack // prints it, & returns
it int area(int, int);
void print(int);
int main()
{
int wid = 8, len = 5, a;

a = area(wid,len);
}
0xbe0 ans
8 int area(int w, int l)
area 0xbe4 w {
5 int ans = w * l;
0xbe8 l print(ans);
004000ca0 return ans;
0xbec Return
link
}
0xbf0 8
wid
0xbf4 5 void print(int
main len
area)
0xbf8 a {
00400120 Return
cout << “Area is
0xbfc link “ << area;
Local variables
10

Variables declared inside function or block, {…},


are stored on the stack
// Computes rectangle area,
Stack // prints it, & returns
it int area(int, int);
void print(int);
int main()
0xbd8 {
print
40 area int wid = 8, len = 5, a;
Return
0xbdc 004001844 link
a = area(wid,len);
40 }
0xbe0 ans
8 int area(int w, int l)
area 0xbe4 w {
5 int ans = w * l;
0xbe8 l print(ans);
004000ca0 return ans;
0xbec Return
link
}
0xbf0 8
wid
0xbf4 5 void print(int
main len
area)
0xbf8 a {
00400120 Return
cout << “Area is
0xbfc link “ << area;
Local variables
11

Variables declared inside function or block, {…},


are stored on the stack
// Computes rectangle area,
Stack // prints it, & returns
it int area(int, int);
cout … void print(int);
int main()
0xbd8 {
print
40 area int wid = 8, len = 5, a;
Return
0xbdc 004001844 link
a = area(wid,len);
40 004000ca0 }
0xbe0 ans
8 int area(int w, int l)
area 0xbe4 w {
5 int ans = w * l;
0xbe8 l print(ans);
004000ca0 return ans;
0xbec Return
link
004001844
}
0xbf0 8
wid
0xbf4 5 void print(int
main len
area)
0xbf8 a {
00400120 Return
cout << “Area is
0xbfc link “ << area;
Local variables
12

Variables declared inside function or block, {…},


are stored on the stack
// Computes rectangle area,
Stack // prints it, & returns
it int area(int, int);
cout … void print(int);
int main()
0xbd8 {
print
40 area int wid = 8, len = 5, a;
Return
0xbdc 004001844 link
a = area(wid,len);
40 }
0xbe0 ans
8 int area(int w, int l)
area 0xbe4 w {
5 int ans = w * l;
0xbe8 l print(ans);
004000ca0 return ans;
0xbec Return
link
}
0xbf0 8
wid
0xbf4 5 void print(int
main len
area)
0xbf8 a {
00400120 Return
cout << “Area is
0xbfc link “ << area;
Local variables
13

Variables declared inside function or block, {…},


are stored on the stack
// Computes rectangle area,
Stack // prints it, & returns
it int area(int, int);
void print(int);
int main()
{
int wid = 8, len = 5, a;

a = area(wid,len);
40 }
0xbe0 ans
8 int area(int w, int l)
area 0xbe4 w {
5 int ans = w * l;
0xbe8 l print(ans);
004000ca0 return ans;
0xbec Return
link
}
0xbf0 8
wid
0xbf4 5 void print(int
main len
area)
0xbf8 a {
00400120 Return
cout << “Area is
0xbfc link “ << area;
Local variables
14

Variables declared inside function or block, {…},


are stored on the stack
// Computes rectangle area,
Stack // prints it, & returns
it int area(int, int);
void print(int);
int main()
{
int wid = 8, len = 5, a;

a = area(wid,len);
}
int area(int w, int l)
{
int ans = w * l;
print(ans);
return ans;
}
0xbf0 8
wid
0xbf4 5 void print(int
main len
area)
40
0xbf8 a {
00400120 Return
cout << “Area is
0xbfc link “ << area;
Scope example
15

Addres
#include <iostream> s
using namespace std; 0 Code


int x = 5;
Global
x=5
int main() {

int m, n = 3, x = 2;

cout << n << "\t" << x << endl; Hea


p
cout << ::x << endl;

}
 Local variables
doit:

 Defined inside a function or block {…}
(x= 3=>2)
 Used inside the same function or block
 Global variables
main:
 Defined outside any function fffffffc (m, n=3,x=2)
 Used by all functions
Memory (RAM)
 When variables share the same name, the closest declaration will be used.
Pointer & Reference
16

Pointer
• Memory address of a variable
• &obj returns the address of obj
• *ptr returns the object at address given by ptr
• *(&obj) returns obj

NULL
• Pointer value points nowhere
• Is 0. So, we can have
• int * p = NULL;
• if(p)
• Defined in <cstdlib>

nullptr
• The NULL pointer defined in C++11
• To use nullptr compatible with C++11
• g++ -std=c++11 -g -o helloPilot helloPilot.cpp
Pointer & Reference
17

Reference
• Is an alias to an existing variable
• Must be initialized when it is declared
• Logically, reference does not consume memory, it is just another name (alias ) of
some variable.
• Physically, it may be implemented by pointer.
Use pointers correctly
18 14

One function can use pointer to modify the int area(int, int, int*);
variable in a different function.
int main()
{
int wid = 5, len = 4, a;
area(wid,len,&a);
Stack Area of }
RAM
void area(int w, int l,
5 int* p)
0xbe0 w {
0xbe4 4 *p = w * l;
area l }
0xbe8 0xbf8
p
0xbec 004000ca0 Return
link

0xbf0 5 wid
main 0xbf4 4 len
20
0xbf8 a
Return
0xbfc 00400120 link
Misuse of pointers
19

int * area(int, int);


Make sure you do not let the pointer pointing to
a wrong address or a dead variable. int main()
{
int wid = 5, len = 4, *a;
You may be lucky to get the value, maybe not. a = area(wid,len);
cout << *a << endl;
}
Stack Area of
RAM int* area(int w, int l)
{
20 int ans = w * l;
0xbe0 ans
5 return &ans;
area 0xbe4 w }
0xbe8 4
l
0xbec 004000ca0 Return
link

5
0xbf0 wid
main 0xbf4 4 len
0xbf8 a
0xbfc 00400120 Return
link
Use Reference, as a variable
20

Reference is an alias for an existing variable.


Variable “r” is alias for variable “x”.
• Here “x” and “r” are labels used by human
being
• “x” and “r” themselves do not take any
memory
• Compiler and linker will map “x” and “r”
to a memory address

int x = 10; x: x == r
10
int &r = x; r: &x == &r
Use Reference, as a parameter
21

Reference is an alias for an existing variable. int area(int, int, int&);

Variable “ans” is an alias for variable “a” in


int main()
the main function. {
int wid = 5, len = 4, a;
a = area(wid,len, a);
cout << a << endl;
}
Stack Area of
RAM void area(int w, int l, int &ans)
{
0xbf8 ans = w * l;
0xbe0 ans }
0xbe4 5
area w
0xbe8 4
l
0xbec 004000ca0 Return
link

5
0xbf0 wid
main 0xbf4 4 len
20
0xbf8 a
0xbfc 00400120 Return
link
Parameters
22

#include <iostream> Addres


s
using namespace std;
0 Code

int a=10; …
0x101e300e0 Global
void foo(int x, int y){ a = 10
cout << x << "\t" << y << endl;
} …

void bar(int *m, int &n){ Hea


*m = 100; p
n = 200; …
cout << &n << endl; …
} bar:
(m=&c,n=&a)
doit:
(x= 3=>2)
foo:
int main(){ (x=10,y=20)
int c = 10, d =20;
main:
0x7fff5ddd1b1c
(c=10,
foo(c, d); fffffffc d=20)
bar(&c, a); Memory (RAM)
}
Parameters
23

#include <iostream>
using namespace std;

int a=10;

void foo(int x, int y){


cout << x << "\t" << y << endl;
}

void bar(int *m, int &n){


Pass by value:
*m = 100;
n = 200; By default, arguments in C++ are
cout << &n << endl; passed by value. When an
} argument is passed by value, the
argument's value is copied into
int main(){ the function's parameter. When
int c = 10, d =20; foo() is called, variable x and y
are created, and values of c and d
foo(c, d);
are copied to x and y.
bar(&c, a);
}
Parameters
24

#include <iostream>
using namespace std;

int a=10;

void foo(int x, int y){


cout << x << "\t" << y << endl;
}
Pass by pointer:
void bar(int *m, int &n){ When bar() is called, variable m is
*m = 100; created, and the address of c is
n = 200; copied to m.
cout << &n << endl;
}

int main(){
int c = 10, d =20;

foo(c, d);
bar(&c, a);
}
Parameters
25

#include <iostream>
using namespace std;

int a=10;

void foo(int x, int y){


cout << x << "\t" << y << endl;
}
Pass by reference:
void bar(int *m, int &n){ When bar() is called, variable n is
*m = 100; created, and n becomes alias to a.
n = 200; In fact, the address of a is copied
cout << &n << endl; to n.
}

int main(){
int c = 10, d =20;

foo(c, d);
bar(&c, a);
}
When to use pass by value, pass by pointers, pass by
reference?
26

Pass by value:
• Do not want to modify the parameter.
• It is easy to copy (int, double, std::string, std::vector, etc.)

Pass by pointer:
• expensive to copy the data
• NULL can be the address value

Pass by reference:
• expensive to copy the data
• NULL cannot be the address value

Pass by pointer vs. pass by reference


• Fundamentally, they work in the same way
• Pass by reference is preferred
• Pass by pointer is used only when it is necessary
Dynamic memory & heap
27

• Memory locations have address 0


Code
• Code is located at low addresses
• Global variables are located after code …
• System stack: memory for each function call Data segment Globals
• Parameters, local variables …
• Return address (where to return)
• etc. Heap
• Usually, NO CODE on the stack
• Heap: Memory can be allocated and de-allocated during
program execution (dynamically at run-time) based on the
needs of the program. …
• Heap grows downward, stack grows upward
• If your program uses up memory, heap and stack
collide, program aborts. … Stack
(area for
data local to
fffffffc a function)

Memory
Static vs. dynamic
28

Automatic/local variables Dynamic allocation

Store in stack or data segment Store in heap

Deallocated (die) when they go out of Valid until explicitly deallocated by the
the scope program (via ‘delete’)

In general, the size is constant and must Size can be determined at run-time
be known at compile time
int count;
int student[24]; cin >> count;
int *student = new int[count];
Dynamic memory in C
29

void * malloc(int num_bytes)


• Function defined in stdlib.h
• Allocates num_bytes of bytes and return a pointer to the allocated block of memory
free(void* ptr)
• Function defined in stdlib.h
• Return the memory pointed by ptr. The memory will be re-used by subsequent
malloc calls

#include<stdio.h>
#include<stdlib.h>

int main()
{
int *ptr;

ptr = (int *)malloc(sizeof(int));

*ptr = 25;
Both gcc and g++
free(ptr);
return 0; can compile this
} code
Dynamic memory in C++
30

new
• Allocates memory from heap
• Returns a pointer to the memory
• double *ptr = new double;
• int *array = new int[24];

delete
• Returns the memory to heap
• followed by the pointer to the data that you want to deallocate
• delete ptr;
• delete [] ptr; // ptr is a pointer to an array
Dynamic memory allocation
31

0 Code

#include <iostream> Globals
using namespace std; …
Heap new
allocates:
int main(int argc, char *argv[]){ 20bc0 00 salary
int count; 20bc4 00 [0]
cin >> count; 20bc8 00 salary[1]
int *salary=new int[count]; 20bcc 00 salary[2]
20bd0 00
delete [] salary; salary[3]
… salary[4]
return 0;
}

stack
fffffffc

Mem
ory
What to fill?
32

• int* • _____ ptr = new int;


• double* • _____ ptr = new double;
• char* • _____ ptr = new char[10];
• char** • _____ ptr = new char*[10];
• color* • _____ ptr = new color;
Dynamic allocation
33

Dynamic Allocation
int area(int, int);
• Stored in heap
• Pointer accesses it int main()
• Exists until user ‘delete’ it {
int wid = 5, len = 4, a;
• If it is not deleted, the data exists in heap even a = area(wid,len);
pointer dies }

Stack Area of Heap Area of int area(int w, int l)


RAM RAM {
0x93c int* ans = new int;
0xbe0 ans *ans = w * l;
0xbe4 5 return *ans;
area w 20
4 0x93c }
0xbe8 l
004000ca0 Return
0xbec link

0xbf0 5
wid
0xbf4 4
main len
0xbf8 a
00400120
0xbfc Return
link
Dynamic allocation
34

Dynamic Allocation
int area(int, int);
• Stored in heap
• Pointer accesses it int main()
• Exists until user ‘delete’ it {
int wid = 5, len = 4, a;
• If it is not deleted, the data exists in heap even a = area(wid,len);
pointer dies }

Stack Area of Heap Area of int area(int w, int l)


RAM RAM {
int* ans = new int;
*ans = w * l;
return *ans;
0x93c 20 }

0xbf0 5
wid
0xbf4 4 Memory Leak
main len
0xbf8 a No pointer to it.
0xbfc 00400120 Return Memory space is
link
wasted.
Dynamic allocation
35

Dynamic Allocation
int area(int, int);
• Stored in heap
• Pointer accesses it int main()
• Exists until user ‘delete’ it {
• If it is not deleted, the data exists in heap even pointer int wid = 5, len =
a = area(wid,len);
4, a;

dies }

Stack Area of Heap Area of int area(int w, int l)


RAM RAM {
0x93c int* ans = new int;
0xbe0 ans ans = &l;
0xbe4 5 return *ans;
area w 20
4 0x93c }
0xbe8 l
004000ca0 Return
0xbec link

0xbf0 5
wid
0xbf4 4
main len
0xbf8 a
00400120
0xbfc Return
link
Dynamic allocation
36

Dynamic Allocation
int area(int, int);
• Stored in heap
• Pointer accesses it int main()
• Exists until user ‘delete’ it {
• If it is not deleted, the data exists in heap even pointer int wid = 5, len =
a = area(wid,len);
4, a;

dies }

Stack Area of Heap Area of int area(int w, int l)


RAM RAM {
0x93c int* ans = new int;
0xbe0 ans ans = &l;
0xbe4 5 return *ans;
area w 20
4 0x93c }
0xbe8 l
004000ca0 Return
0xbec link

0xbf0 5
wid
0xbf4 4 Memory Leak
main len
0xbf8 a No pointer to it.
0xbfc 00400120 Return Memory space is
link
wasted.
Object assignment
37

Assigning one struct or class object to another will cause an element by element copy
of the source data.
#include<iostream>
using namespace std;
enum {CS, MATH, BIO};
struct student { s1 s2
char name[80];
int id; Bill Bill
int major; 5 5
};
int main(int argc, char *argv[]) CS CS
{
student s1;
strncpy(s1.name,”Bill”,80);
s1.id = 5;
s1.major = CS;
student s2 = s1;
return 0;
}
Objects in C++

 Objects can be created as local variables just like any basic data types in C++.
C++:
ComplexType num1;

Java: Nothing equivalent – Objects cannot be in stack.


Objects in Heap
C++:
ComplexType *num1 = new ComplexType(…);
Java:
ComplexType num1 = new ComplexType(…);
Arrays

 Basic data types and classes are treated the same way in C++, unlike Java.

C++: ComplexType colors[5];

Java: nothing equivalent.


C++ array version #2
ComplexNumber *numbers;
numbers = new ComplexNumber[5];

Java: nothing equivalent for classes, but possible


for basic data types:

int numbers[];
numbers = new int[5];

You might also like