Dynamic memory allocation in C (Reek, Ch. 11) 1CS 3090: Safety Critical Programming in C.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Carnegie Mellon 1 Dynamic Memory Allocation: Basic Concepts : Introduction to Computer Systems 17 th Lecture, Oct. 21, 2010 Instructors: Randy Bryant.
Chris Riesbeck, Fall 2007 Dynamic Memory Allocation Today Dynamic memory allocation – mechanisms & policies Memory bugs.
Lecture 10: Heap Management CS 540 GMU Spring 2009.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Growing Arrays in C Language. When to Use Do not use Growing Sorted Array –O(n 2 ) Operation –Avoid when n is large Use Keep track of a variable –Few.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
CS 61C: Great Ideas in Computer Architecture (Machine Structures) Dynamic Memory Management Instructors: Randy H. Katz David A. Patterson
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
1 Memory Allocation Professor Jennifer Rexford COS 217.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III Instructors: Krste Asanovic & Vladimir Stojanovic
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
Finding Bugs with DevPartner Studio Error Detection Philippe CHARMAN Polytech’Nice – Sophia.
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #5 More about.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
1 CS 201 Dynamic Data Structures Debzani Deb. 2 Run time memory layout When a program is loaded into memory, it is organized into four areas of memory.
1 CSE 303 Lecture 11 Heap memory allocation ( malloc, free ) reading: Programming in C Ch. 11, 17 slides created by Marty Stepp
CS 61C: Great Ideas in Computer Architecture Lecture 4: Introduction to C, Part III Instructor: Sagar Karandikar
Pointers Applications
Class 2 CSI2172
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Instructor: Justin Hsia 6/27/2013Summer Lecture #41 CS 61C: Great Ideas in Computer Architecture Memory Management and Usage.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III Instructors: John Wawrzynek & Vladimir Stojanovic
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
ECE Application Programming
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Topics This Section  More C basics  Strings  Functions  Structures  Memory.
1 CSC 211 Data Structures Lecture 6 Dr. Iftikhar Azim Niaz 1.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Memory-Related Perils and Pitfalls in C
CSE 220 – C Programming malloc, calloc, realloc.
Overview of memory management
Dynamic Allocation in C
Object Lifetime and Pointers
Stack and Heap Memory Stack resident variables include:
Nicholas Weaver & Vladimir Stojanovic
Checking Memory Management
CSCI206 - Computer Organization & Programming
Instructors: Michael Greenbaum
Instructor: Michael Greenbaum
CS157: Dynamic Memory Dynamic Memory 11/9/201804/25/06.
Clear1 and Clear2 clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) {
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Memory Allocation CS 217.
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
TUTORIAL 7 CS 137 F18 October 30th.
Dynamic Memory.
Dynamic Memory – A Review
Module 13 Dynamic Memory.
Presentation transcript:

Dynamic memory allocation in C (Reek, Ch. 11) 1CS 3090: Safety Critical Programming in C

Overview of memory management CS 3090: Safety Critical Programming in C2  Stack-allocated memory  When a function is called, memory is allocated for all of its parameters and local variables.  Each active function call has memory on the stack (with the current function call on top)  When a function call terminates, the memory is deallocated (“freed up”)  Ex: main() calls f(), f() calls g() g() recursively calls g() main() f() g()

Overview of memory management CS 3090: Safety Critical Programming in C3  Heap-allocated memory  This is used for persistent data, that must survive beyond the lifetime of a function call  global variables  dynamically allocated memory – C statements can create new heap data (similar to new in Java/C++)  Heap memory is allocated in a more complex way than stack memory  Like stack-allocated memory, the underlying system determines where to get more memory – the programmer doesn’t have to search for free memory space!

Allocating new heap memory CS 3090: Safety Critical Programming in C4 void *malloc(size_t size);  Allocate a block of size bytes, return a pointer to the block ( NULL if unable to allocate block) void *calloc(size_t num_elements, size_t element_size);  Allocate a block of num_elements * element_size bytes, initialize every byte to zero, return pointer to the block ( NULL if unable to allocate block) Note: void * denotes a generic pointer type

Allocating new heap memory CS 3090: Safety Critical Programming in C5 void *realloc(void *ptr, size_t new_size);  Given a previously allocated block starting at ptr,  change the block size to new_size,  return pointer to resized block  If block size is increased, contents of old block may be copied to a completely different region  In this case, the pointer returned will be different from the ptr argument, and ptr will no longer point to a valid memory region  If ptr is NULL, realloc is identical to malloc  Note: may need to cast return value of malloc/calloc/realloc : char *p = (char *) malloc(BUFFER_SIZE);

Deallocating heap memory CS 3090: Safety Critical Programming in C6 void free(void *pointer);  Given a pointer to previously allocated memory,  put the region back in the heap of unallocated memory  Note: easy to forget to free memory when no longer needed...  especially if you’re used to a language with “garbage collection” like Java  This is the source of the notorious “memory leak” problem  Difficult to trace – the program will run fine for some time, until suddenly there is no more memory!

Checking for successful allocation CS 3090: Safety Critical Programming in C7  Call to malloc might fail to allocate memory, if there’s not enough available  Easy to forget this check, annoying to have to do it every time malloc is called...  Reek’s solution: #define mallocDON’T CALL malloc DIRECTLY! #define MALLOC(num,type) (type *)alloc((num)*sizeof(type)) extern void *alloc(size_t size); Garbage inserted into source code if programmer uses malloc Use MALLOC instead... Scales memory region appropriately (Note use of parameters in #define ) Also, calls “safe” alloc function

Checking for successful allocation CS 3090: Safety Critical Programming in C8  implementation of alloc : #undef malloc void *alloc(size_t size) { void *new_mem; new_mem = malloc(size); if (new_mem == NULL) exit(1); return new_mem; }  Nice solution – as long as “terminate the program” is always the right response

Memory errors CS 3090: Safety Critical Programming in C9  Using memory that you have not initialized  Using memory that you do not own  Using more memory than you have allocated  Using faulty heap memory management

Using memory that you have not initialized CS 3090: Safety Critical Programming in C10  Uninitialized memory read  Uninitialized memory copy  not necessarily critical – unless a memory read follows void foo(int *pi) { int j; *pi = j; /* UMC: j is uninitialized, copied into *pi */ } void bar() { int i=10; foo(&i); printf("i = %d\n", i); /* UMR: Using i, which is now junk value */ }

Using memory that you don’t own CS 3090: Safety Critical Programming in C11  Null pointer read/write  Zero page read/write typedef struct node { struct node* next; int val; } Node; int findLastNodeValue(Node* head) { while (head->next != NULL) { /* Expect NPR */ head = head->next; } return head->val; /* Expect ZPR */ } What if head is NULL ?

Using memory that you don’t own CS 3090: Safety Critical Programming in C12  Invalid pointer read/write  Pointer to memory that hasn’t been allocated to program void genIPR() { int *ipr = (int *) malloc(4 * sizeof(int)); int i, j; i = *(ipr ); j = *(ipr ); /* Expect IPR */ free(ipr); } void genIPW() { int *ipw = (int *) malloc(5 * sizeof(int)); *(ipw ) = 0; *(ipw ) = 0; /* Expect IPW */ free(ipw); }

Using memory that you don’t own CS 3090: Safety Critical Programming in C13  Common error in 64-bit applications:  int s are 4 bytes but pointers are 8 bytes  If prototype of malloc() not provided, return value will be cast to a 4-byte int /*Forgot to #include, in a 64-bit application*/ void illegalPointer() { int *pi = (int*) malloc(4 * sizeof(int)); pi[0] = 10; /* Expect IPW */ printf("Array value = %d\n", pi[0]); /* Expect IPR */ } Four bytes will be lopped off this value – resulting in an invalid pointer value

Using memory that you don’t own CS 3090: Safety Critical Programming in C14  Free memory read/write  Access of memory that has been freed earlier int* init_array(int *ptr, int new_size) { ptr = (int*) realloc(ptr, new_size*sizeof(int)); memset(ptr, 0, new_size*sizeof(int)); return ptr; } int* fill_fibonacci(int *fib, int size) { int i; /* oops, forgot: fib = */ init_array(fib, size); /* fib[0] = 0; */ fib[1] = 1; for (i=2; i<size; i++) fib[i] = fib[i-1] + fib[i-2]; return fib; } What if array is moved to new location? Remember: realloc may move entire block

Using memory that you don’t own CS 3090: Safety Critical Programming in C15  Beyond stack read/write char *append(const char* s1, const char *s2) { const int MAXSIZE = 128; char result[128]; int i=0, j=0; for (j=0; i<MAXSIZE-1 && j<strlen(s1); i++,j++) { result[i] = s1[j]; } for (j=0; i<MAXSIZE-1 && j<strlen(s2); i++,j++) { result[i] = s2[j]; } result[++i] = '\0'; return result; } Function returns pointer to stack memory – won’t be valid after function returns result is a local array name – stack memory allocated

Using memory that you haven’t allocated CS 3090: Safety Critical Programming in C16  Array bound read/write void genABRandABW() { const char *name = “Safety Critical"; char *str = (char*) malloc(10); strncpy(str, name, 10); str[11] = '\0'; /* Expect ABW */ printf("%s\n", str); /* Expect ABR */ }

Faulty heap management CS 3090: Safety Critical Programming in C17  Memory leak int *pi; void foo() { pi = (int*) malloc(8*sizeof(int)); /* Allocate memory for pi */ /* Oops, leaked the old memory pointed to by pi */ … free(pi); /* foo() is done with pi, so free it */ } void main() { pi = (int*) malloc(4*sizeof(int)); /* Expect MLK: foo leaks it */ foo(); }

Faulty heap management CS 3090: Safety Critical Programming in C18  Potential memory leak  no pointer to the beginning of a block  not necessarily critical – block beginning may still be reachable via pointer arithmetic int *plk = NULL; void genPLK() { plk = (int *) malloc(2 * sizeof(int)); /* Expect PLK as pointer variable is incremented past beginning of block */ plk++; }

Faulty heap management CS 3090: Safety Critical Programming in C19  Freeing non-heap memory  Freeing unallocated memory void genFNH() { int fnh = 0; free(&fnh); /* Expect FNH: freeing stack memory */ } void genFUM() { int *fum = (int *) malloc(4 * sizeof(int)); free(fum+1); /* Expect FUM: fum+1 points to middle of a block */ free(fum); free(fum); /* Expect FUM: freeing already freed memory */ }

Tools for analyzing memory management CS 3090: Safety Critical Programming in C20  Purify: runtime analysis for finding memory errors  dynamic analysis tool: collects information on memory management while program runs  contrast with static analysis tool like lint, which analyzes source code without compiling, executing it

Reference CS 3090: Safety Critical Programming in C21  S.C. Gupta and S. Sreenivasamurthy. “Navigating ‘C’ in a ‘leaky’ boat? Try Purify” _satish-giridhar/ 822_satish-giridhar/