Week 3
Week 3
Allocation
● Scope
● Malloc
● Calloc
● Realloc
● Alternative to Dynamic
Memory
Scope of a Variable
Three places
Scope of a Variable
Scope of n and m
Scope of a Variable
Scope of g
Lifetime of a local variable
The concept
Out-of-Scope
Dynamic Memory Allocation
The concept
Out-of-Scope
Dynamic Memory Allocation
The concept
Out-of-Scope Out-of-Scope
Dynamic Memory Allocation
The concept
Out-of-Scope Out-of-Scope
Dynamic Memory Allocation
The concept
Out-of-Scope Out-of-Scope
Dynamic Memory Allocation
The concept
Out-of-Scope Out-of-Scope
Dynamic Memory Allocation
The concept
Out-of-Scope Out-of-Scope
The malloc function
According to the 1999 ISO C standard (C99), size_t is an unsigned integer type of at least 16 bit. This type is
used to represent the size of an object.
• https://en.wikipedia.org/wiki/C_data_types#stddef.h
• https://stackoverflow.com/questions/2550774/what-is-size-t-in-c
The malloc function
Usage of malloc function
• Dynamic allocation of
• Array
• Struct
• Factory Methods
Destruction of Dynamic Memory
When is it destroyed?
Out-of-Scope
free( )
The calloc function
Same as malloc
void *calloc(size_t nitems, size_t size)
Automatically initialized
Global Variable Initialization
Automatically initialized
Variable Shadowing
Prevents local variable from being destroyed until the program terminates
The static Keyword
Prevents local variable from being destroyed until the program terminates
Memory Layout of a C Program
Task 1