Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 9 MEMORY MANAGEMENT.

Similar presentations


Presentation on theme: "Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 9 MEMORY MANAGEMENT."— Presentation transcript:

1 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 9 MEMORY MANAGEMENT

2 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Multi-Tasking Provides Motivation Minimizing the amount of global data helps to reduce the probability that the data of one task is accidentally being modified by another. Although memory resource management is of concern in any programming project, it becomes even more crucial for real-time embedded systems.

3 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. How C Defines “Objects” An object is a region of memory that can be examined and stored into. This definition predates object-oriented programming which expands the concept. For the purposes of this course, simply think of objects as variables.

4 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Object Attributes

5 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. SCOPE An Attribute of Identifiers (Variables and Functions)

6 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Taking Advantage of Scope Same identifier may be used for more than one object, as long as they are declared in different scopes. Access is minimized when object is declared in innermost scope.

7 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Global Versus Local int a ; void f( ) { int b ; …. b = ….. …. } A global that can be used by any function. A temporary local only used in function "f". Containing block for ‘b’.

8 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Two Objects - Same Identifier #include void main() { int datum = 1 ; printf("datum=%d\n", datum) ; if ( … ) { int datum = 2 ; printf("datum=%d\n", datum) ; } printf("datum=%d\n", datum) ; } Scope of the 1st object begins at the point of declaration and ends at the closing brace of the function. Scope of the 2nd object. Impossible for statements outside this block to damage this object. Hides the 1st object declared with the same name in outer block.

9 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Global Identifiers Must be declared outside of all functions. Scope is from point of declaration to end of file. Note: Function names are inherently global since no function is ever declared inside another.

10 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Accessing External Variables (Defined in Other Files) /* Define and initialize in only one file */ int a = 123 ; void f1( ) { ….. } /* Separate file requiring access … */ extern int a ; /* no initialization here! */ void f2( ) { a = …. /* external reference */ } Move extern declaration inside function f2 to minimize scope.

11 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Restricting Access to Variables A variable declared with the static keyword is local to the file: #include … int x ; static int foo() { … } #include … static int y ; int bar() { … } file1.c file2.c Accessible only within this file. Accessible from within other files!

12 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Accessing External Functions (Defined in Other Files) double foo(char a, int x) { ….. } extern double foo(char, int) ; void bar( ) { …. y = foo(c, 32) ; …. } Function prototype tells compiler how to use foo. “extern” is not required (default). Moving extern declaration of function inside function bar does NOT reduce its scope!

13 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Restricting Access to Functions A function declared with the static keyword is local to the file: #include … static int foo() { … } #include … int bar() { … } file1.c file2.c Function foo can only be called within this file! Function bar can be called within any file!

14 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Misuse of Globals If a persistent object is needed by a single function, declare it local to that function. ProtectedDangerous

15 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Lifetime An Attribute of Objects (Variables)

16 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Lifetime Objects are: –Created –Initialized –used, and –destroyed. Lifetime refers to the duration of an object's existence (i.e., when it is accessible).

17 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Lifetime vs. Memory Allocation Choice of allocation method determines how an object is created and destroyed, and thus who is responsible for memory management.

18 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Memory Allocation in C

19 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Memory Allocation in C

20 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Static Memory Allocation (The default outside of functions)

21 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Characteristics of Static Objects Objects are allocated (and possibly initialized) once when program is first loaded into memory. Location in memory never changes during execution of the program - objects not destroyed until the program terminates.

22 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Pros and Cons of Static Advantage: Persistence of values. –Unlike objects that use automatic allocation, a value stored in a static object will remain from one execution of a function to another. Disadvantage: Inability to reclaim memory. –Extensive use of static objects can result in programs that require lots of memory.

23 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Static versus Global Every global object is a static object! –Avoiding scope restrictions by declaring all objects global ultimately produces very "fat" programs. Every static object is not necessarily global! –Using global to get persistence isn’t necessary; Just add the keyword static to the local declaration.

24 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. The “static” Keyword Inside a Function: Changes the allocation method from auto (default) to static. Outside of Functions: Has no effect on allocation (remains static), but makes the identifier inaccessible from other files.

25 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Automatic Memory Allocation (The default inside of functions, and not available outside.)

26 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Characteristics of Automatic Objects Objects are allocated on every entry to their containing function. Objects are initialized on every entry to their containing block. Location is fixed during execution of the function, but released when the function is exited. –Functions may return the value of an automatic variable, but not its address.

27 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Pros and Cons of Automatic Advantage: Memory conservation through reuse. –The program manages the sharing of this memory resource automatically. Disadvantage: Lack of persistence.

28 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. The “auto” Keyword Outside Functions: Illegal. Inside Functions: Has no effect on allocation (remains automatic), but it makes the allocation method explicit.

29 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Object Creation (Auto vs. Static) #include void f1() { auto int a ; static int s ; printf(" &auto = %08X\n", &a) ; printf("&static = %08X\n", &s) ; } void f2() { auto int x; f1() ; } int main() { f1() ; f2() ; f1() ; return 0 ;} Program Output: &auto = 0008E8BC &static = 0000BA28 &auto = 0008E89C &static = 0000BA28 &auto = 0008E8BC &static = 0000BA28 Program Output: &auto = 0008E8BC &static = 0000BA28 &auto = 0008E89C &static = 0000BA28 &auto = 0008E8BC &static = 0000BA28

30 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Object Initialization (Auto vs. Static) #include int f1() { auto int a ; a = 0; return ++a ; } int f2() {static int s ; s = 0; return ++s ; } int f3() { auto int a = 0 ; return ++a ; } int f4() {static int s = 0 ; return ++s ; } int main() { printf("f1(): %d %d %d\n", f1(), f1(), f1()) ; printf("f2(): %d %d %d\n", f2(), f2(), f2()) ; printf("f3(): %d %d %d\n", f3(), f3(), f3()) ; printf("f4(): %d %d %d\n", f4(), f4(), f4()) ; return 0 ; } Program Output: f1(): f2(): f3(): f4(): Program Output: f1(): f2(): f3(): f4(): 3 2 1

31 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Object Destruction (Auto vs. Static) int *f1(){static int s = ; return &s ;} int *f2(){ auto int a = ; return &a ;} void Demo(int *(*f)()) { int *p = (*f)() ; printf("Address=%08X, Contents=%d\n", p, *p) ; printf("\n") ; } int main() { Demo(f1) ; Demo(f2) ; return 0 ;} Program Output: Address=0008E88C, Contents=12345 Address=0000AECC, Contents=12345 Address=0000AECC, Contents= Program Output: Address=0008E88C, Contents=12345 Address=0000AECC, Contents=12345 Address=0000AECC, Contents=583820

32 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Register Allocation (A special case of automatic)

33 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Pros and Cons of Register Advantage: Faster Access to Value Disadvantage: Knowing when to use register allocation is not obvious. –Register allocation is local within each function. When another function is called all register variables must be preserved. This overhead often offsets any performance gain.

34 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. The “register” Keyword Example: register unsigned index ; Outside Functions: Illegal. Inside Functions: Attempts to change allocation from automatic (default) to register for faster access; cannot apply “address-of” operator.

35 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Dynamic Memory Allocation (Programmer’s Responsibility)

36 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Allocating Dynamic Memory void *malloc(int bytes) ; Allocates an un-initialized block of memory from the “heap” and returns a pointer to the first byte. The pointer is usually recast and saved in a pointer to data of the desired type. A null pointer is returned when insufficient heap space is available.

37 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Releasing Dynamic Memory void free(void *pointer2block) ; De-allocates the block and returns it to the heap for reuse. Don’t use contents of block after release!

38 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Using Dynamic Memory #include /* required to use malloc and free.*/ #define NULL((void ) 0)/* may not be defined in stdlib.h*/ … typedef … ANYTYPE ; …. ANYTYPE *p ; p = (ANYTYPE *) malloc( sizeof(ANYTYPE) ) ;/* object is created */ if (p == NULL) Error("Insufficient heap space") ; …. …. The object is initialized and used here via the pointer. …. free(p) ;/* object is destoyed */ Object Lifetime

39 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Pros and Cons of Dynamic Advantage: Persistence of static allocation and memory conservation through reuse. Disadvantage: Programmer’s responsibility to release memory; failure to do results in a slow "memory leak" that can be very difficult to debug.

40 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Fragmentation Example: Need 500 bytes 836 free bytes total available in heap Largest single free block is 324 bytes Allocation fails. Use “Pool-Based” allocation scheme or alloca() instead

41 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Pool-Based Allocation Memory pool: A set of equal-size memory blocks. Use multiple pools, each with a different block size. Allocate entire blocks (round up odd size requests). Programmer predetermines block sizes & #blocks.

42 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. alloca() (Automatic with variable size)

43 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Characteristics of alloca() Allocation: Programmer computes size and calls library function alloca (like dynamic). Location: Memory is allocated from the stack (like automatic). Release: “Automatic” upon return from function that called alloca.

44 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Using alloca() FILE *OpenFile(char *name, char *ext, char *mode) { int size = strlen(name) + strlen(ext) + 2 ; char *filespec = (char *) alloca(size) ; FILE *fp ; sprintf(filespec, “%s.%s”, name, ext) ; fp = fopen(filespec, mode) ; if (fp != NULL) return fp ; printf(“Can’t open file: %s!\n”, filespec) ; return NULL ; } Stack pointer is automatically restored on any return, releasing the memory. Stack pointer is decreased by “size” bytes.

45 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Pros and Cons of alloca() Advantages: –Very fast: simply adjusts the stack pointer register. –Release is automatic (no “memory leaks”). Disadvantages: –No indication of allocation failure. –No persistence of values (just like automatic). –Not a standard feature of C.

46 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Variable Size Arrays (Similar to alloca but without the call)

47 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Using Variable Size Arrays FILE *OpenFile(char *name, char *ext, char *mode) { char filespec[strlen(name) + strlen(ext) + 2] ; FILE *fp ; sprintf(filespec, “%s.%s”, name, ext) ; fp = fopen(filespec, mode) ; if (fp != NULL) return fp ; printf(“Can’t open file: %s!\n”, filespec) ; return NULL ; } Not supported by all C compilers!

48 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Variable Size Arrays vs. alloca() Allocation: –VSA is allocated only once on entry to block. –Function alloca() allocates on every call. Release: –VSA is released at end of scope. –Memory allocated with alloca() is released when function returns.

49 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Automatic Allocation and Recursive Functions (Parameters use automatic too)

50 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Recursion & Memory Allocation Recursive functions call themselves. Each call allocates new memory for parameters and local automatics Multiple sets of locals and parameters may exist at the same time. void PutHex(unsigned n) { static char digits[ ] = " ABCDEF" ; if (n > 0xF) PutHex(n / 16) ; putchar(digits[n % 16]) ; }

51 Copyright © 2000, Daniel W. Lewis. All Rights Reserved. Recursive Calls & Allocation 0123?? Enter PutHex(0x123); Enter PutHex(0x12); ? Enter PutHex(0x1); Exit PutHex(0x1); released Exit PutHex(0x12); 0123released Exit PutHex(0x123); released


Download ppt "Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 9 MEMORY MANAGEMENT."

Similar presentations


Ads by Google