Chapter 14. Memory API (1)
Chapter 14. Memory API (1)
Memory API
Operating System: Three Easy Pieces
1
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
#include <stdlib.h>
Return
none
2KB
pointer
heap
(free)
stack int *pi; // local variable
*pi
16KB
Address Space
2KB
allocated
2KB + 4
allocated
2KB + 8
allocated
2KB + 12
allocated pi = (int *)malloc(sizeof(int)* 4);
(free)
2KB *pi
2KB
freed
2KB + 4
freed
2KB + 8
freed
2KB + 12 free(pi);
freed
(free)
2KB(invalid) *pi
16KB
Address Space
2KB
heap
(free)
stack
2KB(invalid) *pi
Incorrect code
char *src = “hello”; //character string constant
char *dst; //unallocated
strcpy(dst, src); //segfault and die
hello\0
heap
strcpy(dst, src);
(free) unallocated
stack
*dst
*src
Address Space
Correct code
char *src = “hello”; //character string constant
char *dst (char *)malloc(strlen(src) + 1 ); // allocated
strcpy(dst, src); //work properly
hello\0 hello\0
allocated hello\0
*dst *dst
*src *src
Address Space Address Space
h
e
strlen l
6 bytes
l
o
\0
*dst
*src
heap heap
(free) (free)
stack stack
*x *x
Address Space Address Space
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
#include <stdlib.h>
Return
Success : a void type pointer to the memory block allocated by calloc
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
#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
#include <unistd.h>
#include <sys/mman.h>