. Plab – Tirgul 4 structs & arrays, file I/O, debugging memory errors.

Slides:



Advertisements
Similar presentations
Week 5 Part I Kyle Dewey. Overview Exam will be back Thursday New office hour More on functions File I/O Project #2.
Advertisements

Recitation By yzhuang, sseshadr. Agenda Debugging practices – GDB – Valgrind – Strace Errors and Wrappers – System call return values and wrappers – Uninitialization.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
Lecture 3 Interfaces Pointers to Functions Memory bugs, File I/O Variables – the special kind.
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.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
Command line arguments. – main can take two arguments conventionally called argc and argv. – Information regarding command line arguments are passed to.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
CPSC 441 Tutorial TA: Fang Wang Introduction to C.
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
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.
Lone Leth Thomsen Input / Output and Files. April 2006Basis-C-8/LL2 sprintf() and sscanf() The functions sprintf() and sscanf() are string versions of.
Recitation 9: Error Handling, I/O, Man Andrew Faulring Section A 4 November 2002.
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.
Characters and Strings File Processing Exercise C Programming:Part 3.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
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:
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.
(language, compilation and debugging) David 09/16/2011.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
C Programming Lecture 12 : File Processing
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
Recitation 9: Error Handling, I/O, Man Anubhav Gupta Section D.
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Recitation 9: 11/04/02 Outline Error Handling I/O Linux man pages Annie Luo Office Hours: Thursday 6:00 – 7:00 Wean 8402.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
Files A collection of related data treated as a unit. Two types Text
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.
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
6/9/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 10 (C-4)
Structs & typedef. Structs 2 Contiguously-allocated region of memory Refer to members within structure by names Members may be of different types Example:
Object Oriented Programming Lecture 2: BallWorld.
Real Numbers Device driver process within the operating system that interacts with I/O controller logical record 1 logical record 2 logical record 3.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Error handling I/O Man pages
C Primer.
Chapter 22 – part a Stream refer to any source of input or any destination for output. Many small programs, obtain all their input from one stream usually.
An Introduction to C Programming
Structs & typedef Already seen in tirgul.
CSC215 Lecture Input and Output.
CS111 Computer Programming
Programming in C Input / Output.
File I/O We are used to reading from and writing to the terminal:
CSC215 Lecture Input and Output.
CSC215 Lecture Input and Output.
Exam 4 review Copyright © 2008 W. W. Norton & Company.
Programming and Data Structure
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.
File Handling.
Programming in C Input / Output.
File I/O & UNIX System Interface
CS1100 Computational Engineering
CSc 352 File I/O Saumya Debray Dept. of Computer Science
15213 C Primer 17 September 2002.
I/O CS580U - Fall 2018.
Structs & typedef Already seen in tirgul.
Professor Jodi Neely-Ritz University of Florida
File I/O We are used to reading from and writing to the terminal:
Presentation transcript:

. Plab – Tirgul 4 structs & arrays, file I/O, debugging memory errors

Assignment: struct vs. pointer to struct x=7 Complex c1, c2; c1.x=7; c1.y=3; c2 = c1; y=3 x=7 y=3 c1c2 Complex *cp1, *cp2; cp1 = (Complex*)malloc... cp2 = (Complex*)malloc... cp1->x=7; cp1->y=3; cp2 = cp1; x=7 y=3 garbage cp1cp2 struct Complex { double x,y; };

u When an array is passed as an argument to a function, the address of the 1 st element is passed. u Structs are passed by value, exactly as the basic types. Arrays & structs as arguments

struct MyStr { int a[10]; }; void f(int a[]) { a[7] = 89; } void g(MyStr s) { s.a[7] = 84; } main() { MyStr x; x.a[7] = 0; f(x.a); printf("%d\n", x.a[7]); g(x); printf("%d\n", x.a[7]); } Output: 89

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. u 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

Default function arguments u We can specify default value for trailing arguments of a function.  An alternative to overloading.  Example: print(int value, int base=10) {... print(31, 16); print(31);// equivalent to print(31,10) h(int x=0, int y) // error! Only in C++

File I/O u 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

. Memory related bugs Memory leaks. Accessing random/freed memory addresses (e.g. off-by-one errors).

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. u 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 u 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. u The program must:  be compiled with –g flag  #include

mtrace example The program: #include int main() { mtrace(); // later we can call muntrace()... The trace 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 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. u 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 u Purify u BoundsChecker u MS’s VisualStudio