Memory-Related Perils and Pitfalls in C

Slides:



Advertisements
Similar presentations
Instructors: Seth Copen Goldstein, Franz Franchetti, Greg Kesden
Advertisements

CSCI 171 Presentation 11 Pointers. Pointer Basics.
Some topics in Memory Management
1 Dynamic Memory Allocation: Advanced Concepts Andrew Case Slides adapted from Jinyang Li, Randy Bryant and Dave O’Hallaron Joke of the day: Why did the.
Mark and Sweep Algorithm Reference Counting Memory Related PitFalls
Carnegie Mellon 1 Dynamic Memory Allocation: Advanced Concepts : Introduction to Computer Systems 18 th Lecture, Oct. 26, 2010 Instructors: Randy.
CSE 451: Operating Systems Section 1. Why are you here? 9/30/102.
Today More on memory bugs Java vs C, the battle..
Dynamic Memory Allocation II Nov 7, 2002 Topics Explicit doubly-linked free lists Segregated free lists Garbage collection Memory-related perils and pitfalls.
– 1 – Dynamic Memory Allocation – beyond the stack and globals Stack Easy to allocate (decrement esp) Easy to deallocate (increment esp) Automatic allocation.
Dynamic Memory Allocation I May 21, 2008 Topics Simple explicit allocators Data structures Mechanisms Policies.
Pointers and Memory Allocation – part 2 -L. Grewe.
Dynamic Memory Allocation II November 7, 2007 Topics Explicit doubly-linked free lists Segregated free lists Garbage collection Review of pointers Memory-related.
Dynamic Memory Allocation II March 27, 2008 Topics Explicit doubly-linked free lists Segregated free lists Garbage collection Review of pointers Memory-related.
University of Washington Memory Allocation III The Hardware/Software Interface CSE351 Winter 2013.
Debugger Presented by 李明璋 2012/05/08. The Definition of Bug –Part of the code which would result in an error, fault or malfunctioning of the program.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Computer Science Detecting Memory Access Errors via Illegal Write Monitoring Ongoing Research by Emre Can Sezer.
University of Washington Today Finished up virtual memory On to memory allocation Lab 3 grades up HW 4 up later today. Lab 5 out (this afternoon): time.
SPL – Practical Session 2 Topics: – C++ Memory Management – Pointers.
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
Dynamic Memory Allocation II
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Dynamic Memory Allocation II Topics Explicit doubly-linked free lists Segregated free lists Garbage collection.
Memory Allocation Alan L. Cox Objectives Be able to recognize the differences between static and dynamic memory allocation Be able to use.
Dynamic Memory Allocation II April 1, 2004 Topics Explicit doubly-linked free lists Segregated free lists Garbage collection Memory-related perils and.
Dynamic Memory Allocation II November 4, 2004 Topics Explicit doubly-linked free lists Segregated free lists Garbage collection Memory-related perils and.
1 Debugging (Part 2). “Programming in the Large” Steps Design & Implement Program & programming style (done) Common data structures and algorithms Modularity.
1 C Basics Monday, August 30, 2010 CS 241. Announcements MP1, a short machine problem, will be released today. Due: Tuesday, Sept. 7 th at 11:59pm via.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Announcements Partial Credit Due Date for Assignment 2 now due on Sat, Feb 27 I always seem to be behind and get tons of daily. If you me and.
University of Washington Today More memory allocation!
Dynamic Memory Management Winter 2013 COMP 2130 Intro Computer Systems Computing Science Thompson Rivers University.
1 Advanced Topics. 2 Outline Garbage collection Memory-related perils and pitfalls Suggested reading: 9.10, 9.11.
Dynamic Memory Allocation II March 27, 2008 Topics Explicit doubly-linked free lists Segregated free lists Garbage collection Review of pointers Memory-related.
Carnegie Mellon 1 Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition Dynamic Memory Allocation: Advanced Concepts :
Programming in C Advanced Pointers.
CSE 220 – C Programming malloc, calloc, realloc.
Dynamic Allocation in C
Using SMGCPA for the Detection of Memory Safety Bugs in the Linux Kernel Anton Vasilyev.
Object Lifetime and Pointers
Instructor: Fatma CORUT ERGİN
Dynamic Memory Allocation II
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
YAHMD - Yet Another Heap Memory Debugger
Instructors: Roger Dannenberg and Greg Ganger
Memory Allocation III CSE 351 Spring 2017
Dynamic Memory Allocation II Nov 7, 2000
Memory Management: Dynamic Allocation
Checking Memory Management
Memory Management III: Perils and pitfalls Oct 14, 1999
CSCI206 - Computer Organization & Programming
The Hardware/Software Interface CSE351 Winter 2013
Memory Allocation III CSE 351 Autumn 2017
Lecture 6 C++ Programming
Dynamic Memory Allocation – beyond the stack and globals
Dynamic Memory Allocation: Advanced Concepts /18-213/14-513/15-513: Introduction to Computer Systems 20th Lecture, November 2, 2017.
Memory Allocation III CSE 351 Autumn 2016
Memory Management III: Perils and pitfalls Mar 13, 2001
Memory Management III: Perils and pitfalls Mar 9, 2000
Memory Allocation III CSE 351 Winter 2018
Dynamic Allocation in C
Memory Allocation III CSE 351 Summer 2018
Pointer & Memory Allocation Review
Memory Allocation III CSE 351 Spring 2017
Memory Allocation III CSE 351 Spring 2017
Memory Bugs, Java and C CSE 351 Winter 2019
Memory Allocation III CSE 351 Autumn 2018
Dynamic Memory – A Review
Presentation transcript:

Memory-Related Perils and Pitfalls in C !!! Memory-Related Perils and Pitfalls in C Dereferencing bad pointers Reading uninitialized memory Overwriting memory Referencing nonexistent variables Freeing blocks multiple times Referencing freed blocks Failing to free blocks

Dereferencing Bad Pointers The classic scanf bug int val; ... scanf(“%d”, val); Fix: should be &val, not val.

Dereferencing Bad Pointers The classic scanf bug Will cause scanf to interpret contents of val as an address! Best case: program terminates immediately due to segmentation fault Worst case: contents of val correspond to some valid read/write area of virtual memory, causing scanf to overwrite that memory, with disastrous and baffling consequences much later in program execution int val; ... scanf(“%d”, val); Fix: should be &val, not val.

Reading Uninitialized Memory Assuming that heap data is initialized to zero /* return y = Ax */ int *matvec(int **A, int *x) { int *y = (int *)malloc( N * sizeof(int) ); int i, j; for (i=0; i<N; i++) { for (j=0; j<N; j++) { y[i] += A[i][j] * x[j]; } return y; Fix: explicitly zero y[i], or use calloc().

Overwriting Memory Allocating the (possibly) wrong sized object int **p; p = (int **)malloc( N * sizeof(int) ); for (i=0; i<N; i++) { p[i] = (int *)malloc( M * sizeof(int) ); } Fix: p = malloc(N * sizeof(int *)).

Overwriting Memory Off-by-one error int **p; p = (int **)malloc( N * sizeof(int *) ); for (i=0; i<=N; i++) { p[i] = (int *)malloc( M * sizeof(int) ); } Fix: i < N, rather than i <= N.

Overwriting Memory Not checking the max string size Basis for classic buffer overflow attacks Your lab assignment #3 char s[8]; int i; gets(s); /* reads “123456789” from stdin */ Fix: use fgets().

Overwriting Memory Misunderstanding pointer arithmetic int *search(int *p, int val) { while (p && *p != val) p += sizeof(int); return p; } Fix: should be p++.

Overwriting Memory Referencing a pointer instead of the object it points to ‘--’ and ‘*’ operators have same precedence and associate from right-to-left, so -- happens first! int *getPacket(int **packets, int *size) { int *packet; packet = packets[0]; packets[0] = packets[*size - 1]; *size--; // what is happening here? reorderPackets(packets, *size); return(packet); } Fix: should be (*size)--. gcc will raise a warning for this line of code only if -Wall is used: gcc -Wall lecture22.c lecture22.c: In function ‘getPacket’: lecture22.c:5:2: warning: value computed is not used [-Wunused-value]

Referencing Nonexistent Variables Forgetting that local variables disappear when a function returns int *foo () { int val; return &val; } Fix: allocate val dynamically, rather than as a local variable.

Freeing Blocks Multiple Times Nasty! x = (int *)malloc( N * sizeof(int) ); <manipulate x> free(x); ... y = (int *)malloc( M * sizeof(int) ); <manipulate y> Fix: free(x) just once. Difficult to diagnose / resolve because free() itself doesn’t (can’t) return any errors – errors are only encountered later on!

Freeing Blocks Multiple Times Nasty! What does the free list look like? x = (int *)malloc( N * sizeof(int) ); <manipulate x> free(x); ... y = (int *)malloc( M * sizeof(int) ); <manipulate y> Fix: free(x) just once. Difficult to diagnose / resolve because free() itself doesn’t (can’t) return any errors – errors are only encountered later on! x = (int *)malloc( N * sizeof(int) ); <manipulate x> free(x);

Referencing Freed Blocks Evil! x = (int *)malloc( N * sizeof(int) ); <manipulate x> free(x); ... y = (int *)malloc( M * sizeof(int) ); for (i=0; i<M; i++) y[i] = x[i]++; Fix: free(x) after the for loop…

Failing to Free Blocks (Memory Leaks) Slow, silent, long-term killer! foo() { int *x = (int *)malloc(N*sizeof(int)); ... return; } Fix: free(x) before returning.

Failing to Free Blocks (Memory Leaks) Freeing only part of a data structure struct list { int val; struct list *next; }; foo() { struct list *head = (struct list *)malloc( sizeof(struct list) ); head->val = 0; head->next = NULL; <create and manipulate the rest of the list> ... free(head); return; } Fix: save next = head->next before free(head), then free next (and all other nodes following it) too…

Dealing With Memory Bugs Conventional debugger (gdb) Good for finding bad pointer dereferences Hard to detect the other memory bugs Debugging malloc (UToronto CSRI malloc) Wrapper around conventional malloc Detects memory bugs at malloc and free boundaries Memory overwrites that corrupt heap structures Some instances of freeing blocks multiple times Memory leaks Cannot detect all memory bugs Overwrites into the middle of allocated blocks Freeing block twice that has been reallocated in the interim Referencing freed blocks

Dealing With Memory Bugs (cont.) Some malloc implementations contain checking code Linux glibc malloc: setenv MALLOC_CHECK_ 2 FreeBSD: setenv MALLOC_OPTIONS AJR Binary translator: valgrind (Linux), Purify Powerful debugging and analysis technique Rewrites text section of executable object file Can detect all errors as debugging malloc Can also check each individual reference at runtime Bad pointers Overwriting Referencing outside of allocated block

What about Java or ML or Python or …? In memory-safe languages, most of these bugs are impossible. Cannot perform arbitrary pointer manipulation Cannot get around the type system Array bounds checking, null pointer checking Automatic memory management But one of the bugs we saw earlier is possible. Which one?

Memory Leaks with GC not because of forgotten free() -- we have GC! unneeded “leftover” roots keep objects reachable Sometimes nullifying a variable is not needed for correctness but is for performance. Bigger issue with reference counting GC. Root nodes Heap nodes reachable Not-reachable (garbage)