40 likes | 170 Views
Chapter 14 Memory API. Chien -Chung Shen CIS, UD cshen@cis.udel.edu. Types of M emory. Stack (or automatic) memory – managed implicitly by compiler for programmer void func () { int x; // declares an integer on the stack ... } Heap memory – explicitly managed by programmer
E N D
Chapter 14Memory API Chien-Chung Shen CIS, UD cshen@cis.udel.edu
Types of Memory • Stack (or automatic) memory – managed implicitly by compiler for programmer void func() { intx; // declares an integer on the stack ... } • Heap memory – explicitly managed by programmer void func() { int*x = (int *) malloc(sizeof(int)); ... }
Size of Memory Allocation int *x = malloc(10 * sizeof(int)); printf("%d\n", sizeof(x)); inty[10]; printf("%d\n", sizeof(y)); • there is enough static information for compiler to know that 40 bytes have been allocated • sizeof()is a compile-time operator
Memory Bugs • Forget to allocate memory char *src= "hello”; char *dst; // oops! unallocated strcpy(dst, src); // segfault and die • Not allocate enough memory char *src= "hello"; char *dst= (char *) malloc(strlen(src)); // too small! strcpy(dst, src); // work properly, but buffer overflow • Forget to initialize allocated memory • Forget to free memory – memory leak