Professional Documents
Culture Documents
Zili Shao
The Course Organization (Bottom-up)
File System
Persistence HW#4
IO Devices and Storage
OS provides services
via System Call
(typically a few
hundred) to run
process, access
memory/devices/files
, etc.
#include <sys/mman.h>
User programming should not directly call them but use memory API (library
functions) – we will study how to utilize them to develop simple memory API
when we study “Memory Management” later.
Memory API: malloc()
#include <stdlib.h>
Return
Success : a void type pointer to the memory block allocated by malloc
Routines and macros are utilized for size in malloc instead typing in a
number directly.
int x[10];
printf(“%d\n”, sizeof(x));
40
Memory API: free()
#include <stdlib.h>
Return
none
Common Error: Forgetting To Allocate Memory
Incorrect code
char *src = “hello”; //character string constant
char *dst; //unallocated
strcpy(dst, src); //segfault and die
hello
heap
strcpy(dst, src);
(free) unallocated
stack
*dst
*src
Address Space
Common Error: Forgetting To Allocate Memory(Cont.)
Correct code
char *src = “hello”; //character string constant
char *dst (char *)malloc(strlen(src) + 1 ); // allocated
strcpy(dst, src); //work properly
hello hello
allocated hello
*dst *dst
*src *src
Address Space Address Space
Common Error: Not Allocating Enough Memory
h
e
strlen
6 bytes l
l
o
\0
*dst
*src
Address Space
Common Error: Forgetting to Initialize
heap heap
(free) (free)
stack stack
*x *x
Address Space Address Space
Common Error: Memory Leak
allocated unused
heap heap
unused
heap
(free) allocated
(free)
stack (free)
stack *d
*c
*b *b
*a *a *a
Address Space Address Space Address Space
*b free()
*b unreachable
*a *a
dangling pointer
2KB 2KB
3KB 3KB
3KB 4KB 3KB
freed
free(b)
4KB 4KB
NULL NULL
Heap Heap
(free) (free)
Stack Stack
*b 3KB *b 3KB
*a 2KB *a 2KB
Address Space Address Space
Common Error: Double Free
2KB 2KB
allocated freed
Heap Heap
free(x) free(x)
Undefined
(free) (free)
Error
Stack Stack
2KB *x 2KB(invalid)
16KB 16KB *x
Address Space Address Space
Other Memory APIs: calloc()
#include <stdlib.h>
Allocate memory on the heap and set with zero before returning.
Argument
size_t num : number of blocks to allocate
Return
Success : a void type pointer to the memory block allocated by calloc
#include <stdlib.h>
Argument
void *ptr: Pointer to memory block allocated with malloc, calloc or realloc
Return
Success: Void type pointer to the memory block
Free: free()
Re-allocation: realloc()