Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chien-Chung Shen CIS/UD

Similar presentations


Presentation on theme: "Chien-Chung Shen CIS/UD"— Presentation transcript:

1 Chien-Chung Shen CIS/UD cshen@udel.edu
Chapter 14 Memory API Chien-Chung Shen CIS/UD

2 Crux: How to Allocate and Manage Memory
In Unix/C programs, understanding how to allocate and manage memory is critical in building robust and reliable software

3 Types of Memory In running a C program, two types of memory are allocated Stack (or automatic) memory – managed implicitly by compiler for programmer (allocation/deallocation) void func() { int x; // declares an integer on the stack ... } Heap memory – explicitly managed by programmer int *p = (int *) malloc(sizeof(int)); free(p); The may cause of many bugs (segmentation faults)

4 malloc() int *x = malloc(10 * sizeof(int)); printf("%d\n", sizeof(x));
int y[10]; printf("%d\n", sizeof(y)); sizeof() is a compile-time operator (i.e., the actual size is known at compile time) [so that it is not a function call, as a function call would take place at run-time] How big a pointer to an integer is (4 or 8); not how much memory was dynamically allocated There is enough static information for compiler to know that 40 bytes have been allocated

5 malloc() Returns [a pointer to type void] (i.e., void *)
Cast the return type of malloc() to [a pointer to a specific type] int *x = (int *) malloc(10 * sizeof(int)); Casting doesn’t really accomplish anything, other than tell the compiler and other programmers who might be reading your code: “yeah, I know what I’m doing.” By casting the result of malloc(), the programmer is just giving some reassurance; the cast is not needed for the correctness

6 free() void func() { int *p = (int *) malloc(sizeof(int)); ... free(p); } The size of the allocated region is not passed in by the user, and must be tracked by the memory-allocation library itself

7 Memory Bugs (Character) strings!!! 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)); strcpy(dst, src); Use malloc(strlen(src) + 1) for extra end-of-string character Forget to initialize allocated memory Forget to free memory – memory leak // too small! // buffer overflow

8


Download ppt "Chien-Chung Shen CIS/UD"

Similar presentations


Ads by Google