slides - Boston University

Download Report

Transcript slides - Boston University

Dynamic Memory Management
CAS CS210
Ying Ye
Boston University
Program in Memory
Taken from
Likai Liu
Memory Allocation
 Static memory allocation:
 done at compile-time
 allocated on stack
 memory size known before compilation
 freed automatically
Memory Allocation
int prod(int x, int y)
{
str1 s1;
str2 s2;
s1.a = x;
s1.p = &y;
s2 = word_sum(s1);
return s2.sum * s2.diff;
}
pushl
movl
subl
leal
leal
movl
movl
movl
movl
call
subl
movl
imull
leave
ret
%ebp
%esp, %ebp
$20, %esp
12(%ebp), %edx
-8(%ebp), %ecx
8(%ebp), %eax
%eax, 4(%esp)
%edx, 8(%esp)
%ecx, (%esp)
word_sum
$4, %esp
-4(%ebp), %eax
-8(%ebp), %eax
Memory Allocation
 Dynamic memory allocation:
 done during run-time
 allocated on heap
 size of memory not necessarily known before compilation
 freed manually
Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int size, *buf;
scanf("%d", &size);
buf = (int *)malloc(sizeof(int) * size);
/* some other operations */
......
free(buf);
return 0;
}
Linux Interface
 void *malloc(size_t size);
allocates size bytes and returns a pointer to the allocated
memory, the memory is not initialized
 void free(void *ptr);
frees the memory space pointed to by ptr, which must have
been returned by a previous call to malloc
 void *calloc(size_t nmemb, size_t size);
 void *realloc(void *ptr, size_t size);
 Download http://cs-people.bu.edu/yingy/alloc.c
Allocate an integer array of size 5,
store integers 1-5 in it,
print them out in reverse order
buf = (int *)malloc(sizeof(int) * 5);
int i;
for(i = 0; i <5; i++)
buf[i] = i + 1;
for(i = 4; i >= 0; i--)
printf("%d\n", buf[i]);
free(buf);
 Download http://cs-people.bu.edu/yingy/linkedlist.c
Singly linked list implementation