C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a ‘wrappered function’? –What is a clean interface? –How to earn your.

Slides:



Advertisements
Similar presentations
Numerical Recipes The Art of Scientific Computing (with some applications in computational physics)
Advertisements

C Programming lecture 2 Beautiful programs Greek algorithms
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Programming in C Chapter 10 Structures and Unions
Recitation By yzhuang, sseshadr. Agenda Debugging practices – GDB – Valgrind – Strace Errors and Wrappers – System call return values and wrappers – Uninitialization.
CSC241 Object-Oriented Programming (OOP) Lecture No. 9.
Lecture 20 Arrays and Strings
CSc 352 Programming Hygiene Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
C Programming - Lecture 5
Kernighan/Ritchie: Kelley/Pohl:
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
C Programming - Lecture 7 This lecture we will learn: –How to write documentation. Internal docs. External docs. User docs. (But not much about this).
API Design CPSC 315 – Programming Studio Fall 2008 Follows Kernighan and Pike, The Practice of Programming and Joshua Bloch’s Library-Centric Software.
CSE 451: Operating Systems Section 1. Why are you here? 9/30/102.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
Object References. Objects An array is a collection of values, all of the same type An object is a collection of values, which may be of different types.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Security Exploiting Overflows. Introduction r See the following link for more info: operating-systems-and-applications-in-
C Course Lecture 4 This lecture we'll talk about: Multi-dimensional arrays. Pointer arithmetic. Pointers to structures. Multi-file programming. What is.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
C Basic File Input/Output Manipulation C Programming – File Outline v File handling in C - opening and closing. v Reading from and writing to files.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
Parsing and Validating Text Input file opening and closing fprintf, fscanf and sscanf fgets and fputs fgetc and putc Parsing a Token Delimited Input Record.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Hank Childs, University of Oregon May 13th, 2015 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / / / __.
C Programming (the Final Lecture) How to test your code really works. How to earn your fortune illegally through computer crime (Do not do this bit). The.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
UFS003C3 Lecture 15 Data type in C & C++ Using the STL.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a wrappered function? –How to assess efficiency. –What is a clean interface?
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Files A collection of related data treated as a unit. Two types Text
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
User-Written Functions
Protecting Memory What is there to protect in memory?
University of Washington Computer Programming I
C Basics.
Files I/O, Streams, I/O Redirection, Reading with fscanf
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
C Programming - Lecture 5
C Programming - Lecture 3
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

C Programming - Lecture 6 This lecture we will learn: –Error checking in C –What is a ‘wrappered function’? –What is a clean interface? –How to earn your fortune illegally with computer crime. (Well, not really.)

Error checking in programs A good programmer always checks file reading, user input and memory allocation (see later) for errors. Nothing convinces a user of your program that you're an idiot faster than it crashing when they type "the wrong thing". Take some action to avert the error even if that action is stopping the program. It is best to print errors to the stderr stream. fprintf (stderr,"There is an error!\n");

What should I check and what should I do? Check any operation that could fail. Check every time a file is opened or memory is allocated. Check user input unless there is no possible way this could break the program. In the case of out of memory it is usually best just to print an error exit(-1); In the case of user input then give them a second chance. In the case of file names it may be a user input problem.

The classic user input errors Could a user input cause something to run off the end of an array or overflow a variable (too big)? Is it a problem if the user input is negative or very tiny? (too small). Is there a possibility of a divide by zero? (exactly too medium sized). In 1998 the guided-missile carrier USS Yorktown was shut down for several hours when a crew- member mistakenly input zero to one of the computers.

Wrappered function Isn't it pretty boring to write an error check every time you try a malloc? Most of the time, after all, you just say "out of memory" and exit. It seems like lots of effort to write the same bit of code every time. The solution is to write your own "wrappered" malloc. You might want to "wrapper" other functions (for example file open).

safe_malloc #include void *safe_malloc (size_t); /* Error trapping malloc wrapper */ void *safe_malloc (size_t size) /* Allocate memory or print an error and exit */ { void *ptr; ptr= malloc(size); if (ptr == NULL) { fprintf (stderr, "No memory line:%d file:%s\n", __LINE__, __FILE__); exit(-1); } return ptr; }

Good programming practice "a clean interface" Interface in this sense means the functions you provide and how they are accessed. A good programmer makes their code useful to other programmers. The best way to do this is to write reusable functions which are easy to understand. If your functions are good then there shouldn't be _too_ many arguments passed to them. Think about "what do I need to pass to this function" and "what do I need back from it". If you have written a clean interface then your functions will almost explain themselves.

Example structure pay.h Header file - enums, structs, prototypes pay.cpp #include "pay.h" int main() Get user input Call appropriate routine fileio.cpp #include "pay.h" Read records when called Writes records Make backup copies update.cpp #include "pay.h" Type in a new file for a new lecturer Change file for existing lecturer printout.cpp #include "pay.h" Print a cheque run for all lecturers Print records of individual lecturers for inspection

By using structs, we can make our functions look simpler Sometimes we need to pass a LOT of information to a function. void write_record (FILE *fptr, char name[], int wage, int hire_date, int increment_date, int pay_scale, char address[]) /* Function to write info about a lecturer */ { } void write_record (FILE *fptr, LECTURER this_lecturer) /* Function to write info about a lecturer */ { } Nicer to bundle it as a struct - and we can add stuff later

Functions should be "consistent" If you write a lot of similar functions it is best to make them work the "same way" int write_record (char fname[],LECTURER lect) /* Return -1 for FAIL 0 for success */ { } int add_record (LECTURER lect, char fname[]) /* Return 0 for FAIL 1 for success */ { } The second function is perverse given the first Another programmer reading your code will be justified in anything short of actual bodily harm if your code works like this.

Functions should be predictable Don't make your function change arguments it doesn't NEED TO. Unless your function is explicitly supposed to change arrays, DON'T change the array. FILE *fptr; char fname[]= "file.txt"; fptr= fopen (fname, "r"); if (fptr == NULL) { printf ("Can't open %s\n",fname); return -1; } Wouldn't you be annoyed if fopen had unexpectedly changed what was in fname?

How to hack into computers Computer hacking - "cracking" as it is correctly called - involves illegally accessing computers. Usually this involves finding an exploit or bug in the operating system of the computer. Operating systems (Windows/Unix/Mac OS) all have these exploits. This shows (amongst other things) the importance of checking user input.

Buffer Overflow Exploits By far the majority of modern "exploits" are "buffer overflows". What happens to this code if it is given a longer string in str2 than str1? void strcpy(char str1[], char str2[]) /* Copy to str1 from str2 */ { int i= 0; while ((str1[i]= str2[i]) != '\0') i++; } Another complex line which assigns and compares.

Where do buffer overflows come from? Here are just some common ways that buffer overflows might arise –Incautious use of "strcpy" (copying a potentially larger string into a smaller one). –Use of the gets command instead of fgets from stdin (which is why I didn't even teach you about gets). –Forgetting to check array bounds on input strings.

So how does a buffer overflow work. Computer memory The array we are about to overflow Some other junk The bits of the program that are being run What we write to the array Lots of "no operations"Our evil program After writing to the array, the program tries to continue but has been overwritten with our evil program

So what do you do? (or not do) Find some program which you can access which has the correct permissions and a "buffer overflow exploit“. Send your data containing your evil program to the input of the bugged program. In 1988 the "Internet Worm" used this method (the gets function) to place self-replicating code which automatically hacked computers. The majority of the internet overloaded and shut down when the worm ran out of control. More recently Code Red worm (2001) SQL Slammer work (2003).