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%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
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 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 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 Singly linked list implementation