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?

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

C Programming lecture 2 Beautiful programs Greek algorithms
Linked Lists.
Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
C Language.
Recitation By yzhuang, sseshadr. Agenda Debugging practices – GDB – Valgrind – Strace Errors and Wrappers – System call return values and wrappers – Uninitialization.
Dynamic Memory Management
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
C Programming - Lecture 5
Kernighan/Ritchie: Kelley/Pohl:
1 Optimizing Malloc and Free Professor Jennifer Rexford COS 217 Reading: Section 8.7 in K&R book
C Programming - Lecture 3 File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How.
More on Dynamic Memory Allocation Seokhee Jeon Department of Computer Engineering Kyung Hee University 1 Illustrations, examples, and text in the lecture.
Compiler Construction
C Programming - Lecture 7 This lecture we will learn: –How to write documentation. Internal docs. External docs. User docs. (But not much about this).
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.
API Design CPSC 315 – Programming Studio Fall 2008 Follows Kernighan and Pike, The Practice of Programming and Joshua Bloch’s Library-Centric Software.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
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.
1 Inner Workings of Malloc and Free Professor Jennifer Rexford COS 217.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Introduction to C Programming CE Lecture 19 Linear Linked Lists.
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.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C Programming –Application of Pointers to Linked List and Binary Tree In this lecture we learn about: –Linked Lists –Binary Trees.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
C Course Lecture 4 This lecture we'll talk about: Multi-dimensional arrays. Pointer arithmetic. Pointers to structures. Multi-file programming. What is.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
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.
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.
C Programming (the Final Lecture) How to document your code. The famous travelling salesman problem (and when a problem is _really_ hard). Three ways to.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
CSC 211 Data Structures Lecture 13
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
1 Homework HW5 due today Review a lot of things about allocation of storage that may not have been clear when we covered them in our initial pass Introduction.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Lecture 8a: File I/O BJ Furman 21MAR2011. Learning Objectives Explain what is meant by a data stream Explain the concept of a ‘file’ Open and close files.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
1 Chapter 6 Methods for Making Data Structures. 2 Dynamic Arrays in Data Structures In almost every data structure, we want functions for inserting and.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Programming Fundamentals Enumerations and Functions.
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.
Advanced Pointers and Structures Pointers in structures Memory allocation Linked Lists –Stacks and queues Trees –Binary tree example.
Data Structure and Algorithm: CIT231 Lecture 6: Linked Lists DeSiaMorewww.desiamore.com/ifm1.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
User-Written Functions
5.13 Recursion Recursive functions Functions that call themselves
A bit of C programming Lecture 3 Uli Raich.
Optimizing Malloc and Free
Linked List Lesson xx   In this presentation, we introduce you to the basic elements of a linked list.
Java Programming Language
C Programming - Lecture 5
C Programming - Lecture 3
Linked lists Low-level (concrete) data structure, used to implement higher-level structures Used to implement sequences/lists (see CList in Tapestry) Basis.
Presentation transcript:

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? –How can structures contain other structures? –What is a linked list?

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");

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 (though this is less common).

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; }

The O-notation The O-notation is used to approximate the efficiency of an algorithm. If we say that the execution time is O(f(n)) we mean: Note therefore that: though generally we specify the execution time in the strongest possible terms

O-notation (getting the feel) nlg nn lg nn 1.25 n2n ,0481,02465,536 4, ,15232,76816,777,216 65,536161,048,5651,048,4764,294,967,296 1,048, ,969,52033,554,4321,099,301,922,576 16, 775, , 614,784 1,073, 613, ,421,292, 179,456

O-notation Inserting into an array – an O(n) operation

The Travelling Salesman The most famous O(n!) problem is the travelling salesman problem A salesman must visit all of n cities – what is his shortest path to do so? At the moment we must check all of his possible routes (n!/2 – we can divide by 2 due to symmetry) We will hear more about the TSP later.

Other efficiency considerations Fewer characters typed is not more efficient. Sometimes you can trade memory for execution time (e.g. the sieve) Allocating memory (with pointers or arrays) is slow. File access is very slow. Consider your algorithms carefully – see where gains can be made.

Good programming practice "a clean interface" A good programmer makes their code useful to other programmers. The best way to do this is to write useful functions which are easy to use. 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.

What are the rules for writing functions in a "clean interface" The functions should be simple - don't try to force your function to do too much - nor make them too limited. In the is_prime examples, it would be silly to write a function which found the lowest prime from 123 to 142 But it might not be unreasonable to write one which took two numbers and found the lowest prime in that range

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) /* 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?

Structs which contain themselves Sometimes programmers want structs in C to contain themselves. For example, we might design an electronic dictionary which has a struct for each word and we might want to refer to synonyms which are also word structures. word1:run synonym1 synonym2 word2: sprint synonym1 synonym2 word3: jog synonym1 synonym2

How structs can contain themselves Clearly a struct cannot literally contain itself. But it can contain a pointer to the same type of struct struct silly_struct { /* This doesn't work */ struct silly_struct s1; }; struct good_struct { /* This does work */ struct *good_struct s2; };

The linked list - a common use of structs which contain themselves Imagine we are reading lines from a file but don't know how many lines will be read. We need a structure which can extend itself. This is known as a linked list. By passing the value of the head of the list to a function we can pass ALL the information.

How to set up a linked list typedef struct list_item { information in each item struct list_item *nextptr; } LIST_ITEM; This structure (where information is what you want each "node" of your linked list to contain). It is important that the nextptr of the last bit of the list contains NULL so that you know when to stop. NULL head of list

Linked list pros & cons Pro: Can easily add items to the head or middle of the list (tough with array) - good for ordered lists Pro:We can make the list as big as we like Con: Complicated for a beginner to program (don't underestimate this) Con: Hard to find nth element Con: Slightly larger since we store pointer and information More will be said on this useful technique next lecture.