Download Understanding C++ Memory Management: Allocation, Dereferencing, and Dynamic Allocation and more Study notes C programming in PDF only on Docsity!
Structures
Structures
Data aggregates
Data aggregates
Like classes (in Java) except usually contain no
Like classes (in Java) except usually contain no
func
func
Structure members are public (we’ll learn this later)
Structure members are public (we’ll learn this later)
structstruct student_datastudent_data
char char name[30];name[30];
int int age;age;
int int sidsid;;
};}; /* <== DO NOT FORGET the semicolon // <== DO NOT FORGET the semicolon */
typedef
typedef
typedef
typedef
new_type_name;
new_type_name;
struct
struct
student_data
student_data
char char name[30];name[30];
int int age;age;
int int sidsid;;
typedef struct
typedef struct
student_data student;
student_data student;
typedef
typedef
typedef
typedef
new_type_name;
new_type_name;
typedef struct
typedef struct
student_data
student_data
char char name[30];name[30];
int int age;age;
int int sidsid;;
} student; //another way to write the} student; //another way to write the typedeftypedef
Structures
Structures
#include#include <>
typedeftypedef structstruct student_datastudent_data
charchar name[30];name[30];
……
}} student;student;
intint main(main(intint argcargc,, charchar** argvargv[])[]) {{
studentstudent amzaamza;; //or//or structstruct student_datastudent_data amzaamza;;
cincin >>>> amzaamza.name;.name;
cincin >>>> amzaamza.age;.age;
cin
cin
amza
amza .
sid
sid ;
coutcout <<<< “name“name =“=“ <<<< amzaamza.name.name <<<< “,“, ageage =“=“ <<<< amzaamza.age.age <<<< endlendl;;
return
return 0;
Memory Management
Memory Management
A variable lives in some memory location for some time
A variable lives in some memory location for some time
Memory is allocated to variables in two ways
Memory is allocated to variables in two ways
Automatic allocation: through variable declaration
e.g., int i; //allocates 4 bytes for i upon entering scope/function
Dynamic allocation: using new
e.g., new double; //allocates 8 bytes upon calling new
Scope = Enclosing block for a variableScope = Enclosing block for a variable - - could be acould be a funcfunc
oror
artificially created by using {
artificially created by using {
int
int
i; ……} within
i; ……} within
func
func
body
body
Memory Management
Memory Management
A variable lives in some memory location for some time
A variable lives in some memory location for some time
The variable lifetime is
The variable lifetime is
Automatic allocation: within scope
e.g., int i; //while enclosing function instantiation is active
Dynamic allocation: until programmer explicitly frees block
e.g., new double; //until program calls delete (outlives scope)
5 10 12.5 9. 8 c d
Example using automatic allocation:
int x = 5, y = 10; //automatic vars
float f = 12.5, g = 9.8;
char c = ‘c’, d = ‘d’;
Memory layout and addresses
Memory layout and addresses
Pointers
Pointers
Definitions:
Definitions:
“Pointers are variables that hold a memory address”
“Pointers are variables that hold a memory address”
e.g., a pointer
e.g., a pointer
p
p
contains an address
contains an address
addr
addr
The memory address
The memory address
addr
addr
contains another variable
contains another variable
var
var
We say that pointerWe say that pointer pp “points to” variable“points to” variable varvar
Data Representations (revisited)
Data Representations (revisited)
Sizes of C++ Objects (in Bytes)
Sizes of C++ Objects (in Bytes)
Data Type Compaq Alpha Typical Intel IA
int 4 4 4
long int 8 4 4
char 1 1 1
short 2 2 2
float 4 4 4
double 8 8 8
char * 8 4 4
» Or any other pointer
“Word Size” (Convention)“Word Size” (Convention)
Size of integer data (i.e., typically 4 bytes)
Pointer Dereferencing
Pointer Dereferencing
Q: Get the value of the variable “pointed
Q: Get the value of the variable “pointed
to” by pointer
to” by pointer
A: the “indirection” operator: *
A: the “indirection” operator: *
float f = 3.2; //variable of type float
float f = 3.2; //variable of type float
float *p;float *p; //pointer to variable of type float//pointer to variable of type float
p = &f;p = &f;
coutcout << *p;<< *p; //prints the//prints the varvar “pointed“pointed--to” by pto” by p
// (i.e.,
// (i.e.,
var
var
at address p)
at address p)
f p
any float
any address
f p
Using Pointers (1)
Using Pointers (1)
floatfloat f;f; /* data variable // data variable */
float
float
p;
p;
/* pointer variable */
/* pointer variable */
p = &f;p = &f; /* & = address operator // & = address operator */
Pointer Dereferencing
Pointer Dereferencing
Q: Get the value of the variable “pointed
Q: Get the value of the variable “pointed
to” by pointer
to” by pointer
A: the “indirection” (a.k.a. “dereferencing”) operator: *
A: the “indirection” (a.k.a. “dereferencing”) operator: *
float f; //variable of type float
float f; //variable of type float
float *p;float *p; //pointer to variable of type float//pointer to variable of type float
p = 3.2;p = 3.2; //WRONG !!//WRONG !!
//Dereferencing an//Dereferencing an unitializedunitialized pointerpointer
//Typically results in SEGFAULT (bombing)
//Typically results in SEGFAULT (bombing)
Pointers made easy (2)
Pointers made easy (2)
amza
p
4300? e.g., 4300 + sizeof(student)
amza
p
CA| 17| 99| 4300
(p).(p).sidsid == 99;99; // indirection:indirection: amzaamza..sidsid isis nownow 999/999/
(p).age(p).age == 17;17; // amzaamza.age.age isis 1717 //
cincin >>>> (p).name;(p).name; // saysay wewe inputinput “CA”“CA” //
studentstudent amzaamza;; /* data variable // data variable */
studentstudent p;p; /* pointer variable // pointer variable */
p = &p = &amzaamza;; /* use of indirection operator // use of indirection operator */
The Operator (instead of * and .)
The Operator (instead of * and .)
amza
p
99| 17| CA 4300
pp sidsid == 99;99; // indirection:indirection: amzaamza..sidsid isis nownow 999/999/
p
p
age = 17;
age = 17; /*
amza
amza .age is 17 */
.age is 17 */
cincin >>>> pp name;name; // saysay wewe inputinput “CA”“CA” //
studentstudent amzaamza;; /* data variable // data variable */
studentstudent p;p; /* pointer variable // pointer variable */
p = &p = &amzaamza;; /* use of indirection operator // use of indirection operator */
Dynamic Memory Allocation
Dynamic Memory Allocation
Java manages memory for you, C++ does not
Java manages memory for you, C++ does not
In Java programmer allocates with new, but does not free
space (garbage collection in Java)
C++ requires the programmer to explicitly allocate and
deallocate memory
Memory can be allocated dynamically during run-time with
new and deallocated (freed) using delete
Memory
Memory
Memory allocated with new, deMemory allocated with new, de--allocated with deleteallocated with delete
new returns address of (pointer to) allocated blocknew returns address of (pointer to) allocated block
Allocated block
(4 bytes)
Free block
(3 bytes)
Free byte
Allocated byte
The memory allocator provides an abstraction of memory as a set of blocks
delete
delete
Deallocates
Deallocates
memory in heap.
memory in heap.
Pass in a pointer that was returned by new.
Pass in a pointer that was returned by new.
Examples
Examples
Allocate an integer
int* iptr = new int;
delete iptr;
Allocate a structure
struct student_data* amzaptr = new student;
delete amzaptr;
Caveat: don’t free the same memory block twice!
Caveat: don’t free the same memory block twice!
Examples
Examples
typedeftypedef structstruct student_datastudent_data
charchar name[30];name[30]; ……
}} student;student;
typedeftypedef structstruct two_charstwo_chars {{
charchar first_char;first_char;
charchar second_char;second_char;
}} two;two;
typedeftypedef structstruct five_charsfive_chars {{
char
char first_char;
first_char;
char char second_char;second_char; ……
…… charchar fifth_char;fifth_char;
}} five;five;
Allocation/Dealloc. Examples
Allocation/Dealloc. Examples
p1 = new int;
p2 = new struct five_chars;
p3 = new struct six_chars;
delete p2;
p4 = new struct two_chars;
Allocation/Dealloc. Examples
Allocation/Dealloc. Examples
p1 = new int;
p3 = new six;
delete p2;
p4 = new two;
p2 = new five;
p
p
p
p
How about pointers inside structs?
How about pointers inside structs?
typedef structtypedef struct four_chars {four_chars {
charchar first_char;first_char;
charchar second_char;second_char; ……
… charchar fourth_char;fourth_char;
} four;
} four;
typedef struct
typedef struct
four_plus_two_chars {
four_plus_two_chars {
four four **first_four_charsfirst_four_chars;;
two two **last_two_chars;last_two_chars;
} four_plus_two;} four_plus_two;
How about pointers inside structs?
How about pointers inside structs?
p1 = new four_plus_two;
p2 = new four; p1->first_four_chars = p2;
p3 = new two; p1->last_two_chars = p3;
delete p1;
Oops!
Memory leak! (garbage left around, need to delete all
allocated blocks)
Need to allocate nested objects. Need to deallocate them correspondingly.
Easy fix because we kept p2 and p
Easy fix because we kept p2 and p
p1 = new four_plus_two;
p2 = new four; p1->first_four_chars = p2;
p3 = new two; p1->last_two_chars = p3;
delete p2;
Need to allocate nested objects. Need to deallocate them correspondingly.
delete p1;
delete p3;
Usually only pointer to “top” is kept
Usually only pointer to “top” is kept
p1 = new four_plus_two_chars; (“top” pointer to object)
p1->first_four_chars = new four;
p1->last_two_chars = new two;
delete p1;
Need to allocate nested objects. Need to deallocate them correspondingly.
Oops!
Memory leak! (garbage left around, cannot get to
the remaining blocks !!)
Heap Allocator Internals
Heap Allocator Internals
p1 = new four;
p2 = new five;
p3 = new six;
delete p2;
p4 = new six; //cannot allocate a block of 6 bytes
//this allocation fails due to
//“no more heap space”
Memory allocated in a contiguous block. External Fragmentation: when
enough aggregate heap memory, but no single free block is large enough.
Automatic Allocator Internals
Automatic Allocator Internals
Automatic allocation of variables occurs on the stack
Automatic allocation of variables occurs on the stack
We’ll learn how the stack works next
We’ll learn how the stack works next