1 / 10

Dynamic Memory Management

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. pushl %ebp

giza
Télécharger la présentation

Dynamic Memory Management

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 pushl %ebp movl %esp, %ebp subl $20, %esp leal 12(%ebp), %edx leal -8(%ebp), %ecx movl 8(%ebp), %eax movl %eax, 4(%esp) movl %edx, 8(%esp) movl %ecx, (%esp) call word_sum subl $4, %esp movl -4(%ebp), %eax imull -8(%ebp), %eax leave ret 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; }

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

  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

More Related