Lecture 3 Interfaces Pointers to Functions Memory bugs, File I/O Variables – the special kind.

Slides:



Advertisements
Similar presentations
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
Advertisements

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.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
CS414 C Programming Tutorial Ben Atkin
. Plab – Tirgul 2 Const, C Strings. Pointers int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; ijx 1.
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.
. Pointers to functions Debugging. Logistics u Mid-term exam: 18/11  Closed books  List of topics – see web page Some you have to read by yourself!
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
. Plab – Tirgul 4 structs & arrays, file I/O, debugging memory errors.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Guide To UNIX Using Linux Third Edition
. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.
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++)
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Java and C++, The Difference An introduction Unit - 00.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
chap13 Chapter 13 Programming in the Large.
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.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
File Handling Spring 2013Programming and Data Structure1.
22. FILE INPUT/OUTPUT. File Pointers and Streams Declarations of functions that perform file I/O appear in. Each function requires a file pointer as a.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
File IO and command line input CSE 2451 Rong Shi.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
C LANGUAGE Characteristics of C · Small size
Fall 2004CS-183 Dr. Mark L. Hornick 1 C++ Arrays C++ (like Java) supports the concept of collections – mechanisms to sort and manipulate many instances.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
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.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
Object Oriented Programming Lecture 2: BallWorld.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Multiple file project management & Makefile
CSE691 Software Models and Analysis.
Stack and Heap Memory Stack resident variables include:
An Introduction to C Programming
Command-Line Arguments
C Basics.
Instructor: Ioannis A. Vetsikas
Memory Allocation CS 217.
C What you Know* Objective: To introduce some of the features of C. This assumes that you are familiar with C++ or java and concentrates on the features.
SPL – PS2 C++ Memory Handling.
Memory, Arrays & Pointers
Presentation transcript:

Lecture 3 Interfaces Pointers to Functions Memory bugs, File I/O Variables – the special kind

Interfaces A definition of a set of functions that provide a coherent module (or library) –Data structure (e.g., list, binary tree) –User interface (e.g., drawing graphics) –Communication (e.g., device driver)

Interface - modularity Hide the details of implementing the module from its usage –Specification – “what” –Implementation – “how”

Interface – information hiding Hide “private” information from outside –The “outside” program should not be able to use internal variables of the module –Crucial for modularity Resource management –Define who controls allocation of memory

Example interface - StrStack A module that allows to maintain a stack of strings Operations: –Create new –Push string –Pop string –IsEmpty [See attached StrStack.h]

Implementation of StrStack Decision #1: data structure Linked list Array (static? dynamic?) Linked list of arrays … We choose linked list for simplicity

Implementation of StrStack Decision #2: Resource allocation Duplicated strings on stack or keep pointer to original? If duplicate, who is responsible for freeing them? We choose not to duplicate --- leave this choice to user of module

Implementation of StrStack See StrStack.c

Using StrStack int main() { char *Line; StrStack *Stack = StrStackNew(); while( (Line = ReadLine()) != NULL ) StrStackPush( Stack, Line ); while( (Line = StrStackPop(Stack)) != NULL ) { printf("%s\n", Line ); free( Line ); } return 0; }

Interface Principles Hide implementation details Hide data structures Don’t provide access to data structures that might be changed in alternative implementation A “visible” detail cannot be later changed without changing code using the interface!

Interface Principles Use small set of “primitive” actions Provide to maximize functionality with minimal set of operations Do not provide unneeded functions “just because you can”

Interface Principles Don’t reach behind the back Do not use global variables or unexpected side effects Do not assume specific order of operations by the user –Such assumptions suggest the set of primitives is wrong

Interface Principle Consistent Mechanisms Do similar things in a similar way –strcpy(dest, source) –memcpy(dest, source)

Interface Principle Resource Management Free resource at the same level it was allocated Assumptions about resources

Pointers to functions

Pointers to Functions C/C++ allow to have a pointer to a function int foo(int x) {…} main() { int (*func)(int); // func is a pointer to a function func = &foo; func = foo; // same int x = (*func)(7); // same as x = foo(7) }

Example: Numerical Integrator

double numericalIntegration( double a, double b, double (*func)(double), int k ) { double delta = (b - a)/k; double Sum = 0; for( double x = a+0.5*delta; x < b; x+= delta ) Sum += (*func)(x); return Sum*delta; } See NumericalIntergator.c

“Generic” interface Pointers to functions provide a way to write code that receives functions as arguments For example sorting – you can apply different comparison functions –increasing and decreasing order can be computed using the same algorithm code –Different data types can be sorted using the same algorithm code

Example: qsort Library procedure: qsort( void *base, size_t n, size_t size, int (*compare)(void const*, void const *) ); base – start of an array n – number of elements size – size of each element compare – comparison function

Using qsort int compareInt(void const *p, void const *q) { int a = *(int const*)p; int b = *(int const*)q; if( a < b ) return -1; return a > b; } … int array[10] = { … }; qsort( array, 10, sizeof(int), compareInt );

argv & argc To pass command line arguments to our program we should use the following main declaration: main(int argc, char* argv[]) {... Compare to main(String[] args) in java. Unlike java the first argument is the name of the program itself.  char** argv   char argv[][]

argv & argc: example $ prog1 –u danny –p 1234 argc = 5 argv[0] = “prog1” argv[1] = “-u”... argv[4] = “1234” Always: argv[argc] = 0

File I/O File I/O is mostly similar to stdin & stdout I/O. Most I/O functions we encountered have a “file” counterpart which receives a FILE pointer (handle). Examples: getchar(void) fgetc(FILE*) scanf(const char *,...) fscanf(FILE*, const char*,...) printf(const char *,...) fprintf(FILE*, const char*,...) The standard streams ( stdin, stdout, stderr ) are also of FILE* type. See related man pages: fprintf, fscanf, etc.

File I/O example: mywc #include #include #include main(int argc, char* argv[]) { FILE* fp; int wc = 0, ch; if (argc != 2) { printf("Usage: mywc \n"); exit(1); } errno = 0; fp = fopen(argv[1], "r"); if (fp == NULL) { perror(“”); exit(1); }

File I/O example while (1) { while ((ch = fgetc(fp)) != EOF && isspace(ch)) ; if (ch == EOF) break; wc++; while ((ch = fgetc(fp)) != EOF && !isspace(ch)) ; if (ch == EOF) break; } fclose(fp); printf("There are %d words in %s\n", wc, argv[1]); return 0; } Related man pages: fopen, fclose

Inter module variables’ scope

Static variables Static variables in a function keep their value for the next call to the function –Allocated on the heap (1)void getUniqueID() { (2) static int id=0; (3) id++; (4) return id; (5)} (6)int main() { (7) int i = getUniqueID(); //i=1 (8) int j = getUniqueID(); //j=2 (9)}

Static variables, cont. “static” variable on the global scope –Available only in the current module “extern” variable –Defined outside the module file2.c extern int y; //y from file1.c extern int x; //x defined elsewhere int myFunc() { int y; //error … } file1.c int y; static int x; int myFunc() { int x; //error … }

C’s “const” is a qualifier that can be applied to the declaration of any variable to specify its value will not be changed. const double e = ; const char msg[] =“Warning:”; msg[1] = ‘w’; // illegal ! C ’s “const”

Do not confuse what the “const” declaration “protects” ! –A pointer to a const variable: int const * p = {1,2,3}; p[1] = 1; // illegal! *(p+1) = 1; // illegal! p = NULL; //legal –A const pointer to a variable: int* const const_p = {1,2,3}; const_p[1] = 0; // legal ! const_p = NULL; // illegal! C ’s “const”

Pointer’s Syntax Compare: (1)int * const p = {1,2,3}; (2)const int * p = {1,2,3}; (3)int const * p = {1,2,3}; (2) and (3) are synonyms in C to a pointer to a const array. We encourage right to left reading of declarations, to achieve better readability and avoid errors.` DO NOT TRY THIS AT HOME

Pointers and User Defined Types struct Complex { int img; int real; }; Complex comp2; Complex const comp1 = comp2; //ok,initialize using comp2 Complex comp3; comp1.img = 3; // illegal ! comp1 value is constant comp1=comp3; // illegal ! comp1 value is constant All the members of a const variable are immutable !

Compare to Java’s “final” All (methods as well as data ) are Class members. “final” makes primitive types constants and references to objects constant. The values inside the referred objects are not constant ! final int LIMIT = 10; int LIMIT = 11;// illegal ! final MyObject obj1 = MyObject(); MyObject obj2 = NULL; MyObject obj3 = MyObject(); obj2 = obj1;//fine, both point now to the same object obj1 = obj3; // illegal ! obj1.setSomeValue(5); // legal ! * Because All are class members you would normally use them as class constants and declare them as “static final”

“Const” Usage The const declaration can (and should !) be used in the definition of a function’s arguments, to indicate it would not change them: int strlen(const char []); Why use ? (This is not a recommendation but a must) –Clearer code –Avoids errors –Part of the interfaces you define! We will see more of “const” meaning and usage when we get to C++

Memory related bugs Memory leaks. Accessing random/freed memory addresses.

malloc_stats() By including malloc.h you can use the malloc_stats() function which prints to the stderr information about the amount of used memory. Example:... malloc_stats(); destroyDictionary(dict); malloc_stats();...

malloc_stats() cntd. With memory leak: Arena 0: system bytes = 8140 in use bytes = Arena 0: system bytes = 8140 in use bytes = Without memory leak: Arena 0: system bytes = 8124 in use bytes = Arena 0: system bytes = 8124 in use bytes = 4...

mtrace Log all memory allocations to a file. –The file name is contained in the MALLOC_TRACE environment variable. –For example: $setenv MALLOC_TRACE ~/plab/ex1/trace Analyze the file to find memory leaks using the mtrace utility. The program must: –be compiled with –g flag –#include

mtrace example The program: #include int main() { mtrace(); // later we can call muntrace()... muntrace(); return 0; } The log file looks like this: = [0x80486fd] + 0x804a0e0 [0x804887d] + 0x804a0f0 [0x8048c7d] + 0x804a100 /lib/libc.so.6:(__strdup+0x29)[0x400d7a29] + 0x804a118 [0x8048c7d] + 0x804a128 /lib/libc.so.6:(__strdup+0x29)[0x400d7a29] + 0x804a140 [0x8048c7d] + 0x804a150 0x14...

mtrace example cntd. The result of analysis ( mtrace ex1 $MALLOC_TRACE ) Memory not freed: Address Size Caller 0x0804a100 0x14 at /home/mush/plab/ex1/strBinTree.c:65 0x0804a128 0x14 at /home/mush/plab/ex1/strBinTree.c:65 0x0804a150 0x14 at /home/mush/plab/ex1/strBinTree.c:65 Memory not freed: Address Size Caller 0x0804a118 0x5 at /lib/libc.so.6:(__strdup+0x29)[0x400d7a29] 0x0804a140 0x3 at /lib/libc.so.6:(__strdup+0x29)[0x400d7a29] Another example:

MALLOC_CHECK_ By setting this environment variable to 0, 1, 2 we can handle some bugs, most notably freeing twice the same memory. Usually double free causes segmentation fault. When MALLOC_CHECK_ is 0 freeing twice works. When MALLOC_CHECK_ is 1 an error message is printed. –Example: free(): invalid pointer 0x80497b8! When MALLOC_CHECK_ is 2 the program (gracefully) aborts.

ElectricFence u ElectricFence is a library which allows to catch accesses to memory that was already freed, as well as off-by-one errors. u It will cause the program to segfault in the above cases, which is usually better than continue running and have unpredictable errors later. Example: char* a = (char*)malloc(100*sizeof(char));... a[100] = 'c'; // ElectricFence will cause segfault

ElectricFence cntd. Example: Node* n1 = (Node*)malloc(sizeof(Node));... free(n1);... n1->x = 7; // ElectricFence will cause segfault  To use ElectricFence you should link your program with the efence library.  For example: g++ prog1.o list.o read.o -lefence

Commercial products Purify BoundsChecker MS’s VisualStudio