NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

Similar documents
CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING PREVIEW SLIDES 14, SPRING 2013

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 14, FALL 2012

Dynamic Memory Allocation: Advanced Concepts

Dynamic Memory Allocation II October 22, 2008

Memory Allocation III

Internal Fragmentation

Dynamic Memory Alloca/on: Advanced Concepts

Memory Allocation III

Today. Dynamic Memory Allocation: Advanced Concepts. Explicit Free Lists. Keeping Track of Free Blocks. Allocating From Explicit Free Lists

Dynamic Memory Allocation

Memory Allocation III

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Memory Allocation III CSE 351 Spring (original source unknown)

Dynamic Memory Allocation: Advanced Concepts

Dynamic Memory Allocation: Advanced Concepts

Memory Allocation III

Dynamic Memory Allocation

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

Foundations of Computer Systems

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

CS 11 C track: lecture 5

Dynamic Memory Alloca/on: Advanced Concepts

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Dynamic Memory Allocation

Lecture 8 Dynamic Memory Allocation

Dynamic Data Structures. CSCI 112: Programming in C

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

CS61, Fall 2012 Section 2 Notes

In Java we have the keyword null, which is the value of an uninitialized reference type

CSCI 171 Chapter Outlines

Pointers and Memory Management

COSC Software Engineering. Lecture 16: Managing Memory Managers

Class Information ANNOUCEMENTS

Intermediate Programming, Spring 2017*

Dynamic memory allocation (malloc)

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

MPATE-GE 2618: C Programming for Music Technology. Unit 5.1

A brief introduction to C programming for Java programmers

EL2310 Scientific Programming

Memory Management. CSC215 Lecture

Kurt Schmidt. October 30, 2018

Dynamic Allocation in C

o Code, executable, and process o Main memory vs. virtual memory

CS24 Week 2 Lecture 1

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Structures & Dynamic Memory Management

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CS 222: Pointers and Manual Memory Management

Arrays and Memory Management

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

Lecture Notes on Memory Management

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Lecture Notes on Memory Management

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

CMSC 341 Lecture 2 Dynamic Memory and Pointers

Memory (Stack and Heap)

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Intermediate Programming, Spring 2017*

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

DAY 3. CS3600, Northeastern University. Alan Mislove

Data Representation and Storage

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

C Introduction. Comparison w/ Java, Memory Model, and Pointers

CSC C69: OPERATING SYSTEMS

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

Programs in memory. The layout of memory is roughly:

Dynamic Allocation in C

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

CSC 1600 Memory Layout for Unix Processes"

Data Representation and Storage. Some definitions (in C)

Fall 2018 Discussion 2: September 3, 2018

Outline. Briefly review the last class Pointers and Structs Memory allocation Linked lists

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Dynamic memory allocation

Limitations of the stack

Binghamton University. CS-211 Fall Dynamic Memory

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

High Performance Programming Programming in C part 1

Memory Organization. The machine code and data associated with it are in the code segment

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Lecture Notes on Polymorphism

377 Student Guide to C++

Pointers, Arrays, Memory: AKA the cause of those Segfaults

Section Notes - Week 1 (9/17)

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Transcription:

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313 http://www.csee.umbc.edu/courses/undergraduate/313/fall11/"

Programming in C! Advanced Pointers!

Reminder! You can t use a pointer until it points to something! Just declaring a variable to be a pointer is not enough! int *name; /* pointer declaration */ int age = 42;! *name += 12; printf( My age is %d\n, *name); CMSC 313 2

Pointers to Pointers! Since a pointer is a variable type, a pointer may point to another pointer.! Consider the following declarations!!int age = 42;!!/* an int */!!int *page = &age;!/* a pointer to an int */!!int **ppage = &page;!/* a pointer to a pointer to an int */! Draw a memory picture of these variable and their relationships! What type and what value do each of the following represent?! age, page, ppage, *page, *ppage, **ppage! CMSC 313 3

pointers2pointer.c! int main ( ) { /* a double, a pointer to double, ** and a pointer to a pointer to a double */ double gpa = 3.25, *pgpa, **ppgpa; /* make pgpa point to the gpa */ pgpa = &gpa; /* make ppgpa point to pgpa (which points to gpa) */ ppgpa = &pgpa; // what is the output from this printf statement? printf( "%0.2f, %0.2f, %0.2f", gpa, *pgpa, **ppgpa); } return 0; 3.25, 3.25, 3.25 CMSC 313 4

Pointers to struct /* define a struct for related student data */ typedef struct student { char name[50]; char major [20]; double gpa; } STUDENT; STUDENT bob = {"Bob Smith", "Math", 3.77}; STUDENT sally = {"Sally", "CSEE", 4.0}; STUDENT *pstudent; /* pstudent is a "pointer to struct student" */ /* make pstudent point to bob */ pstudent = &bob; /* use -> to access the members */ printf ("Bob's name: %s\n", pstudent->name); printf ("Bob's gpa : %f\n", pstudent->gpa); /* make pstudent point to sally */ pstudent = &sally; printf ("Sally's name: %s\n", pstudent->name); printf ("Sally's gpa: %f\n", pstudent->gpa); CMSC 313 5

Pointer in a struct! The data member of a struct can be any data type, including pointer. The struct person has a pointer to a struct name." " #define FNSIZE 50 #define LNSIZE 40 typedef struct name { char first[ FNSIZE + 1 ]; char last [ LNSIZE + 1 ]; } NAME; typedef struct person { NAME *pname; // pointer to NAME struct int age; double gpa; } PERSON; CMSC 313 6

Pointer in a struct (2)! Given the declarations below, how do we access bob s name, last name, and first name?" Draw a picture of memory represented by these declarations NAME bobsname = { Bob, Smith }; PERSON bob; bob.age = 42; bob.gpa = 3.4; bob.pname = &bobsname; CMSC 313 7

Self-referencing structs! Powerful data structures can be created when a data member of a struct is a pointer to a struct of the same kind.! The simple example on the next slide illustrates the technique.! CMSC 313 8

teammates.c! typedef struct player { char name[20]; struct player *teammate;/* can t use TEAMMATE yet */ } TEAMMATE; TEAMMATE *team, bob, harry, john; team = &bob; /* first player */ strncpy(bob.name, bob, 20); bob.teammate = &harry; /* next teammate */ strncpy(harry.name, harry, 20); harry.teammate = &john; /* next teammate */ strncpy(john.name, bill, 20); john.teammate = NULL: /* last teammate */ CMSC 313 9

teammates.c (cont d)! /* typical code to print a (linked) list */ /* follow the teammate pointers until ** NULL is encountered */ // start with first player TEAMMATE *t = team; // while there are more players... while (t!= NULL) { printf( %s\n, t->name); }! // next player t = t->teammate; CMSC 313 10

Dynamic Memory! C allows us to allocate memory in which to store data during program execution.! Like Java, dynamically allocated memory is take from the heap.! Dynamic memory has two primary applications! Dynamically allocating an array! based on some user input or file data better than guessing and defining the array size in our code since it can t be changed Dynamically allocating structs to hold data in some predetermined arrangement (a data structure)! Allows an infinite amount of data to be stored CMSC 313 11

Dynamic Memory Functions! These functions are used to allocate and free dynamically allocated heap memory and are part of the standard C library. To use these functions, include <stdlib.h>.!! void *malloc( size_t nrbytes ); Returns a pointer to dynamically allocated memory on the heap of size nrbytes, or NULL if the request cannot be satisfied. The memory is uninitialized. void *calloc( int nrelements, size_t nrbytes ); Same as malloc( ), but the memory is initialized to zero Note that the parameter list is different void *realloc( void *p, size_t nrbytes); Changes the size of the memory pointed to by p to nrbytes. The contents will be unchanged up to the minimum of the old and new size. If the new size is larger, the new space is uninitialized. Returns a pointer to the new memory, or NULL if request cannot be satisfied in which case *p is unchanged. void free( void *p ) Deallocates the memory pointed to by p which must point to memory previously allocated by calling one of the functions above. Does nothing if p is NULL. CMSC 313 12

void* and size_t The void* type is C s generic pointer. It may point to any kind of variable, but may not be dereferenced. Any other pointer type may be converted to void* and back again without loss of information. void* is often used as parameter types to, and return types from, library functions.!! size_t is an unsigned integral type that should be used (rather than int) when expressing the size of something (e.g. an int, array, string, or struct). It too is often used as a parameter to, or return type from, library functions. By definition, size_t is the type that is returned from the sizeof( ) operator.! CMSC 313 13

malloc( ) for arrays! malloc( ) returns a void pointer to uninitialized memory.! Good programming practice is to cast the void* to the appropriate pointer type.! Note the use of sizeof( ) for portable coding.! As we ve seen, the pointer can be used as an array name.! int *p = (int *)malloc( 42 * sizeof(int)); for (k = 0; k < 42; k++) p[ k ] = k; for (k = 0; k < 42; k++) printf( %d\n, p[ k ]; Exercise: rewrite this code using p as a pointer rather than an array name! CMSC 313 14

calloc( ) for arrays! calloc( ) returns a void pointer to memory that is initialized to zero.! Note that the parameters to calloc( ) are different than the parameters for malloc( )! int *p = (int *)calloc( 42, sizeof(int)); for (k = 0; k < 42; k++) printf( %d\n, p[k]); CMSC 313 15

realloc( ) realloc( ) changes the size of a dynamically allocated memory previously created by malloc( ) or calloc( ) and returns a void pointer to the new memory.! The contents will be unchanged up to the minimum of the old and new size. If the new size is larger, the new space is uninitialized.!! int *p = (int *)malloc( 42 * sizeof(int)); for (k = 0; k < 42; k++) p[ k ] = k; p = (int *_)realloc( p, 99 * sizeof(int)); for (k = 0; k < 42; k++) printf( p[ %d ] = %d\n, k, p[k]); for (k = 0; k < 99; k++) p[ k ] = k * 2; for (k = 0; k < 99; k++) printf( p[ %d ] = %d\n, k, p[k]);!! CMSC 313 16

Testing the returned pointer! malloc( ), calloc( ) and realloc( ) all return NULL if unable to fulfill the requested memory allocation.! Good programming practice dictates that the pointer returned should be validated!! char *cp = malloc( 22 * sizeof( char ) ); if (cp == NULL) { fprintf( stderr, malloc failed\n); exit( -12 ); } CMSC 313 17

assert( )! Since dynamic memory allocation shouldn t fail unless there is a serious programming mistake, such failures are often fatal.! Rather than using if statements to check the return values from malloc( ), we can use the assert( ) macro.! To use assert( ), you must! #include <assert.h> char *cp = malloc( 22 * sizeof( char ) ); assert( cp!= NULL ); CMSC 313 18

How assert( ) works! The parameter to assert is any Boolean expression!assert( expression ); If the Boolean expression is true, nothing happens and execution continues on the next line! If the Boolean expression is false, a message is output to stderr and your program terminates! The message includes the name of the.c file and the line number of the assert( ) that failed assert( ) may be disabled with the preprocessor directive #define NDEBUG assert( ) may be used for any condition including! Opening files! Function parameter checking (preconditions)! CMSC 313 19

free( ) free( ) is used to return dynamically allocated memory back to the heap to be reused by later calls to malloc( ), calloc( ) or realloc( ) The parameter to free( ) must be a pointer previously returned by one of malloc(), calloc() or realloc( ) Freeing a NULL pointer has no effect! Failure to free memory is known as a memory leak and may lead to program crash when no more heap memory is available! int *p = (int *)calloc(42, sizeof(int)); /* code that uses p */! free( p );! CMSC 313 20

Dynamic Memory for structs! In JAVA public class Person { } public int age; public double gpa; // memory allocation Person bob = new Person( ); bob.age = 42; bob.gpa = 3.5; // bob is eventually freed // by garbage collector In C typedef struct person { int age; double gpa; /* memory allocation */ PERSON *pbob = (PERSON *)malloc(sizeof(person)); pbob->age = 42; pbob->gpa = 3.5;... /* explicitly freeing the memory */ free( pbob ); CMSC 313 21

typedef struct player { char name[20]; Dynamic Teammates! struct player *teammate; } PLAYER; PLAYER *getplayer( ) { } char *name = askuserforplayername( ); PLAYER *p = (PLAYER *)malloc(sizeof(player)); strncpy( p->name, name, 20 ); p->teammate = NULL; return p;! CMSC 313 22

Dynamic Teammates (2)! int main ( ) { int nrplayers, count = 0; PLAYER *pplayer, *pteam = NULL; nrplayers = askuserfornumberofplayers( ); while (count < nrplayers) { pplayer = getplayer( ); pplayer->teammate = pteam; pteam = pplayer; ++count; } /* do other stuff with the PLAYERs */ /* Exercise -- write code to free ALL the PLAYERs */ return 0; }! CMSC 313 23

Dynamic Arrays! As we noted, arrays cannot be returned from functions.! However, pointers to dynamically allocated arrays may be returned.! char *getchararray( int size ) { } char *cp = (char *)malloc( size * sizeof(char)); assert( cp!= NULL); return cp; CMSC 313 24

Dynamic 2-D arrays! There are now three ways to define a 2-D array, depending on just how dynamic you want them to be.! int board[ 8 ] [ 8 ]; An 8 x 8 2-d array of int... Not dynamic at all! int *board[ 8 ]; An array of 8 pointers to int. Each pointer represents a row whose size is be dynamically allocated.! int **board; A pointer to a pointer of ints. Both the number of rows and the size of each row are dynamically allocated.! CMSC 313 25

Memory-Related Perils and Pitfalls! 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.! Typically reported as an error by the compiler.! int val;... scanf( %d, val);

Reading Uninitialized Memory! Assuming that heap data is initialized to zero! /* return y = A times x */ int *matvec(int A[N][N], int x[n]) { 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 i, **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 123456789 from stdin */ Basis for classic buffer overflow attacks! 1988 Internet worm! Modern attacks on Web servers! AOL/Microsoft IM war!

Overwriting Memory! Misunderstanding pointer arithmetic! int *search(int *p, int val) { while (*p!= NULL && *p!= val) p += sizeof(int); } return p;

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

Freeing Blocks Multiple Times! Nasty!! x = malloc(n * sizeof(int)); <manipulate x> free(x); y = malloc( M * sizeof(int)); <manipulate y> free(x);

Referencing Freed Blocks! Evil!! x = malloc(n * sizeof(int)); <manipulate x> free(x);... y = malloc(m * sizeof(int)); for (i = 0; i < M; i++) y[ i ] = x[ i ]++;

Failing to Free Blocks (Memory Leaks)! Slow, long-term killer!! 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; <create and manipulate the rest of the list>... free(head); return; }

Dealing With Memory Bugs! Conventional debugger (gdb)! Good for finding bad pointer dereferences! Hard to detect the other memory bugs! Some malloc implementations contain checking code!! Linux glibc malloc: setenv MALLOC_CHECK_ 2!

Dealing With Memory Bugs (cont.)! Binary translator: valgrind (Linux)! 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 (Boehm-Weiser Conservative GC)! Let the system free blocks instead of the programmer.!