Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dynamic Memory Management CAS CS210 Ying Ye Boston University.

Similar presentations


Presentation on theme: "Dynamic Memory Management CAS CS210 Ying Ye Boston University."— Presentation transcript:

1 Dynamic Memory Management CAS CS210 Ying Ye Boston University

2 Program in Memory Taken from Likai Liu

3 Memory Allocation Static memory allocation:  done at compile-time  allocated on stack  memory size known before compilation  freed automatically

4 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%ebp movl%esp, %ebp subl$20, %esp leal12(%ebp), %edx leal-8(%ebp), %ecx movl8(%ebp), %eax movl%eax, 4(%esp) movl%edx, 8(%esp) movl%ecx, (%esp) callword_sum subl$4, %esp movl-4(%ebp), %eax imull-8(%ebp), %eax leave ret

5 Memory Allocation Dynamic memory allocation:  done during run-time  allocated on heap  size of memory not necessarily known before compilation  freed manually

6 Memory Allocation #include int main(void) { int size, *buf; scanf("%d", &size); buf = (int *)malloc(sizeof(int) * size); /* some other operations */...... free(buf); return 0; }

7 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);

8 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

9 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);

10 Download http://cs-people.bu.edu/yingy/linkedlist.c Singly linked list implementation


Download ppt "Dynamic Memory Management CAS CS210 Ying Ye Boston University."

Similar presentations


Ads by Google