Pointers and Memory Allocation – part 2 -L. Grewe.

Slides:



Advertisements
Similar presentations
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Advertisements

Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
User-Level Memory Management in Linux Programming
Some topics in Memory Management
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.
Kernighan/Ritchie: Kelley/Pohl:
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:
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
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Carnegie Mellon 1 Dynamic Memory Allocation: Advanced Concepts : Introduction to Computer Systems 18 th Lecture, Oct. 26, 2010 Instructors: Randy.
Dynamic Memory Allocation II Nov 7, 2002 Topics Explicit doubly-linked free lists Segregated free lists Garbage collection Memory-related perils and pitfalls.
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 – 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.
Dynamic Memory Allocation II November 7, 2007 Topics Explicit doubly-linked free lists Segregated free lists Garbage collection Review of pointers Memory-related.
Run-time Environment and Program Organization
Dynamic Memory Allocation II March 27, 2008 Topics Explicit doubly-linked free lists Segregated free lists Garbage collection Review of pointers Memory-related.
Pointers Applications
University of Washington Memory Allocation III The Hardware/Software Interface CSE351 Winter 2013.
University of Washington CSE 351 : The Hardware/Software Interface Section 5 Structs as parameters, buffer overflows, and lab 3.
Security Exploiting Overflows. Introduction r See the following link for more info: operating-systems-and-applications-in-
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
Computer Science Detecting Memory Access Errors via Illegal Write Monitoring Ongoing Research by Emre Can Sezer.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
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.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
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.
Dynamic Memory Allocation II
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Dynamic Memory Allocation II Topics Explicit doubly-linked free lists Segregated free lists Garbage collection.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
Sairajiv Burugapalli. This chapter covers three main categories of classic software vulnerability: Buffer overflows Integer vulnerabilities Format string.
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 10 Chapter 10 Implementing Subprograms. Implementing Subprograms  The subprogram call and return operations are together called subprogram linkage.
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.
Memory-Related Perils and Pitfalls in C
Dynamic Allocation in C
Object Lifetime and Pointers
Buffer Overflow Buffer overflows are possible because C doesn’t check array boundaries Buffer overflows are dangerous because buffers for user input are.
Instructor: Fatma CORUT ERGİN
Dynamic Memory Allocation II
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
The Hardware/Software Interface CSE351 Winter 2013
Instructors: Roger Dannenberg and Greg Ganger
Dynamic Memory Allocation II Nov 7, 2000
Checking Memory Management
Memory Management III: Perils and pitfalls Oct 14, 1999
Lecture 6 C++ Programming
Dynamic Memory Allocation – beyond the stack and globals
Memory Management III: Perils and pitfalls Mar 13, 2001
Memory Management III: Perils and pitfalls Mar 9, 2000
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Pointer & Memory Allocation Review
Presentation transcript:

Pointers and Memory Allocation – part 2 -L. Grewe

2 Objectives Pointers to Functions More potential Issues with Pointers - advanced

Pointers to Functions (this is NOT passing pointers as arguments to functions!!! This is a pointer pointing to a function itself!!!!!!) A pointer can also store the address of a function A function name is the address in memory of the start of the function Function pointers can be –Passed to a function –Returned to functions –Stored in arrays –Assigned to other function pointers

An Array of Pointers to Functions #include void fun1(void); void fun2(void); void fun3(void); int main(){ /*declare an array of pointers to functions*/ void (*array[3])(void) = {fun1,fun2,fun3}; int i; for (i=0;i<3;i++) (*array[i])();/*make a function call*/ return 0; /*output: 1st 2nd 3rd */ } void fun1(void){printf("1st ");} void fun2(void){printf("2nd ");} void fun3(void){printf("3rd ");}

Alternative Code #include void fun1(void); void fun2(void); void fun3(void); int main(){ void (*array[3])(void) = {fun1,fun2,fun3}; /*declare an array of pointers to functions*/ int i; for (i=0;i<3;i++) array[i](); /*or (*array[i])(); */ return 0; /*output: 1st 2nd 3rd */ } void fun1(void){printf("1st ");} void fun2(void){printf("2nd ");} void fun3(void){printf("3rd ");}

Pointers to Functions void (*array[3])(void)={fun1,fun2,fun3}; “array” is an array of 3 pointers to 3 functions with no arguments and return type void (*array[i])(void); //THESE ARE THE SAME array[i]();

An Array of Pointers to Functions 2 #include int fun1(int); int fun2(int); int fun3(int); int main(){ int (*array[3])(int) = {fun1,fun2,fun3}; int i; for (i=0;i<3;i++) printf("%d ",(*array[i])(i)); /*1 3 5*/ /* printf("%d ", array[i](i)); */ return 0; } int fun1(int x){return x+1;} int fun2(int x){return x+2;} int fun3(int x){return x+3;} Just some new functions fun1, fun2, fun3 With parameters

Pointers to Functions 2 int (*array[3])(int)={fun1,fun2,fun3}; “array” is an array of 3 pointers to 3 functions with one int argument and return type int (*array[i])(i); array[i](i); The function is dereferenced and integer “i” is passed as an argument to the function

Pointers to functions: WHY? 9 They allow for a certain amount of polymorphism: –“poly” (many) + “morph” (shape) –A polymorphic language can handle a range of different data types (“shapes”?) with a single statement

Pointers to functions: safety concerns 10 What if uninitialized function pointer value is accessed? –Safest outcome: memory error, and program is terminated –But what if the “garbage” value is a valid address? Worst case: address contains program instruction –execution continues, with random results Hard to trace the cause of the erroneous behavior

Pointer and Memory Failures re-visited and Advanced 11

Memory-related bugs Dereferencing bad pointers Reading uninitialized memory Overwriting memory Referencing nonexistent variables Freeing blocks multiple times Referencing freed blocks Failing to free blocks

Reading uninitialized memory Assuming that heap data is initialized to zero /* return y = Ax */ int *matvec(int **A, int *x) { int *y = 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; }

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

Overwriting memory Off-by-one int **p; p = malloc(N*sizeof(int *)); for (i=0; i<=N; i++) { p[i] = malloc(M*sizeof(int)); }

Overwriting memory Not checking the max string size char s[8]; int i; gets(s); /* reads “ ” from stdin */ Basis for classic buffer overflow attacks 1988 Internet worm modern attacks on Web servers AOL/Microsoft IM war

Buffer overflow attacks Description of hole: –Servers that use C library routines such as gets() that don’t check input sizes when they write into buffers on the stack. –The following description is based on the IA32 stack conventions. The details will depend on how the stack is organized, which varies between compilers and machines 64 bytes for buffer return addr Saved regs. and Local vars proc a() { b(); # call procedure b } proc b() { char buffer[64]; # alloc 64 bytes on stack gets(buffer); # read STDIN line into buf } Stack frame for proc a %ebp Stack frame for proc b %ebp increasing addrs

Buffer overflow attacks Vulnerability stems from possibility of the gets() routine overwriting the return address for b. –overwrite stack frame with machine code instruction(s) that execs a shell a bogus return address to the instruction proc a() { b(); # call procedure b } # b should return here, instead it # returns to an address inside of buffer proc b() { char buffer[64]; # alloc 64 bytes on stack gets(buffer); # read STDIN line to buffer } Stack region overwritten by gets(buffer) exec(“/bin/sh”) New return addr Saved regs. and Local vars Stack frame for proc a padding Stack frame for proc b %ebp incr addrs

Overwriting memory Referencing a pointer instead of the object it points to int *BinheapDelete(int **binheap, int *size) { int *packet; packet = binheap[0]; binheap[0] = binheap[*size - 1]; *size--; Heapify(binheap, *size, 0); return(packet); }

Overwriting memory Misunderstanding pointer arithmetic int *search(int *p, int val) { while (*p && *p != val) p += sizeof(int); //you should increment //array by 1 only //you are missing elements return p; }

Referencing nonexistent variables Forgetting that local variables disappear when a function returns int *foo () { int val; return &val; }

Freeing blocks multiple times x = malloc(N*sizeof(int)); // …. free(x); y = malloc(M*sizeof(int)); //… free(x);

Referencing freed blocks x = malloc(N*sizeof(int)); //…. free(x);... y = malloc(M*sizeof(int)); for (i=0; i<M; i++) y[i] = x[i]++;

Failing to free blocks (memory leaks) Run out of memory as you repeatedly call function …foo(), foo(), foo() …. foo() { int *x = malloc(N*sizeof(int));... return; }

Failing to free blocks (memory leaks) Freeing only part of a data structure struct list { int val; struct list *next; }; foo() { struct list *head = malloc(sizeof(struct list)); head->val = 0; head->next = NULL;... free(head); //not freeing other part of list created. return; }

Dealing with memory bugs Conventional debugger (gdb) –good for finding bad pointer dereferences –hard to detect the other memory bugs Debugging 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.) Binary translator (i.e. Purify-IBM product)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 Garbage collection –let the system free blocks instead of the programmer.

Pointer and Memory Allocation Tips Use Pointers only when you need to. Pointer problems can be the most difficult to debug Whenever you allocate memory – think immediately where/if you need to deallocate it Use Data Structures implemented in C++ Collections already provided when possible –as they are written to take care of potential problems like class copying we saw previously. 28