Lecture 5 Flashcards
Memory Allocation
what are the sections of a program’s memory?
stack, heap, read and write data segment, read only data segment
are a program’s sections in memory shared with any other program running?
no, each program gets its own stack, heap, read and write data segment, and read only data segment
what kind of memory are the read & write and read only data segments?
static memory
what 3 types of data does the read only segment store?
machine instructions (aka code), constant global variables, and string literals
what 2 types of data does the read and write segment store?
global and static variables
what is the lifetime of the variables stored in the read only and read & write segments?
1) created when program starts
- stored in these
segments
2) destroyed when program completes
- exits function normally or
abnormally
const double p = 3.14;
double area = 0;
int main() {
static int rad = 10;
area = p * rad;
printf(“%.2f\n”, area);
return 0;
}
what variables are stored in the read only segment?
p and %.2f
(const global and string literal)
const double p = 3.14;
double area = 0;
int main() {
static int rad = 10;
area = p * rad;
printf(“%.2f\n”, area);
return 0;
}
what variables are stored in the read and write segment?
area and rad
(global and static)
what does static do to a variable when defining it?
gives the variable global scope
what does const do to a variable when defining it?
constant variable –> read only
bc cannot change value
- only can access it or “get” it
when is heap memory allocated?
allocated using a function call during code execution
ex)
malloc()
calloc()
realloc()
when is heap memory deallocated?
deallocated using a function call during execution
ex)
free()
what happens when malloc() is called?
1) system goes to heap segment in memory that is assigned to this program
2) OS will try to allocate that amount of bytes in heap
- if space is allocated: returns
pointer that points @ the address
in heap of where the allocated
memory starts (*no initialization
in memory –> leftover values
stored there will fill space)
how does malloc() allocate the correct amount of bytes?
uses sizeof() to help calculate the number of bytes that we want malloc() to allocate
ex) malloc(sizeof(int))
int* p = (int*)malloc(sizeof(int));
what is happening here?
based on the sizeof function calculation, malloc will find 4 bytes in the heap to store this int and return the pointer that points at that location where the int is stored in the heap