Chapter - 17 Debugging and Optimization. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

Size: px
Start display at page:

Download "Chapter - 17 Debugging and Optimization. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1"

Transcription

1 Chapter - 17 Debugging and Optimization Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

2 Debugging Techniques Divide and conquer Debug only code Debug Command Line Switch Note: Use I/O redirection and the editor to browse large volumes of debug output. Interactive Debuggers Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 2

3 Gnu Debugger (gdb) commands: run Start execution of a program. break line-number Insert a breakpoint at the given line number. break function-name Insert a breakpoint at the first line of the named function. cont Continue execution after a breakpoint. print expression Display the value of an expression. Execute a single line in the program. next Execute a single line in the program, skip over function calls. list List the source program. where status delete Print the list of currently active functions. Print out a list of breakpoints Remove a break point. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 3

4 #include int main() /******************************************************** void { ********************************************************/ seven_count; data[5]; three_count; int void get_data(data); for return std::cout std::cin get_data(int { index; <iostream> (index if ++seven_count; " (data[index] Seven's (0); ++three_count; -->> << = = data[1] 1; "Three's "Enter 0; data[]) " 5index data[]); << numbers theinto == seven_count 5>>data[2] <= " numbers\n"; 3) 7) << of the 5; from to three_count seven's ++index) of the >>data[3] threes << */ command '\n'; in 3{ the in << >>data[4] 7the line */ */* >>data[5]; */ A program to debug Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 4

5 Threes % copies under the There "show GDB Copyright break Starting Breakpoint $1 12 $2 Enter 314 (gdb) print $3 7 = count is conditions certain is warranty" main print 50 seven_count 3free ofnumbers 2Sevens absolutely (m68k-sun-sunos4.0.3), program: , software three_count seven_count get_data(data); for conditions; main Free 3 for 0x22c2: (index /usr/sdo/count/count () no details. Software and warranty = file = you count.cc:10 1; type 0; index are Foundation, count.cc, "show for welcome <= GDB; copying" 5; line ++index) to type Inc... distribute 10. to see { When we run this program with the data the results are: GDB run:. First Debugging Session run next next next All right how did seven_count get to 2? Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 5

6 info Num 1 delete The Starting Breakpoint $5 print $6 Enter $7 (gdb) = Type program 3breakpoints 02 it seven_count next 50 print list 1numbers 2 void { from program: 2, 30 std::cout std::cin being seven_count get_data(int the 0x23b2: debugged beginning? /usr/sdo/count/count Disp keep >>data[1] << << (data=0x208f8) file Enb y "Enter data[]) has Address 0x000022c2 0x000023b2 count.cc, (y>>data[2]>>data[3]>>data[4]>>data[5]; been 5or 5 numbers\n"; n) started y line What count.cc:29 main get_data(int 29. already. data[3] count.cc:10 *) data[4] count.cc:29 data[5]; Figuring out what happened The value got change in get_data. Let s look through it. break get_data run next Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 6

7 * #include const intsearch Usage: Files: data[max_numbers]; max_count; char search numbers.dat -- <iostream> <fstream.h> <stdlib.h> <stdio.h> *const Search youdata_file awill --set numbers = (Numbers 1000; // ofasked Array = 1"numbers.dat";// per must of ofmax line valid ordered) toelements lookup search in File search file with in data * numbers Binary Search /******************************************************** ********************************************************/ Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 7

8 ifstream int in_file.open(data_file, cerr exit * while char in_file.getline(line, sscanf(line, Read (in_file.bad()) (in_file.eof()) (data[max_count] middle; low, search; << (8); line[30]; (1) "Error:Unable in_file; high; = { 0; "%d", // { Line data[max_count]); // == to sizeof(line)); Input Middle Upper/lower number -1) ios::in); from open file the to " << our search input bound DATA_FILE search file for range << '\n'; main() { /* */ break; break; ++max_count; Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 8

9 std::cin while middle std::cout if low high return (search (low (data[middle] = = 0; (1) max_count; = middle; (0); == >> (low { << == high) search; "Enter "Found "Not -1) + high) == { < found\n"; search) number at/ index 2; to{ " search << middle for or << -1 '\n'; to quit:" ; break; break; else Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 9

10 Data When we run this program on UNIX, the results are: % search Segmentation fault (core dumped) Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 10

11 % GDB Copyright Starting Program 0xec46320 #0 #1 #2 #3 list (gdb) The runis xec xec45cc2 0xec45b34 0x2400 program search 48free received (m68k-sun-sunos4.0.3), program: 1994 in insoftware isnumber main Free running. in_file.getline(line, sscanf(line, if ++max_count; signal number _doscan /usr/sdo/search/search () (in_file.eof()) (data[max_count] Software () break; and SIGSEGV, () Quit... () search.cc:48 Foundation, "%d", anyway Segmentation data[max_count]); == (and sizeof(line)); -1) Inc... killfault. it)? (y or n) y Debugging Session (gdb) (gdb) where (gdb) quit Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 11

12 % GDB Copyright Starting Breakpoint Program 0xec46320 (gdb) The break search is 4.12 program free const main() { received (m68k-sun-sunos4.0.3), program: , software data[max_numbers]; max_count; int ifstream in_file.open(data_file, is number char main Free (in_file.bad()) running. middle; low, search; 0x2318: in_file.getline(line, sscanf(line, signal /usr/sdo/search/search *const () (in_file.eof()) Software ()... high; in_file; = 0; SIGSEGV, search.cc:24 Quit Foundation, search.cc, "%d", anyway { // Segmentation Array Number Middle Upper/lower number Input data[max_count]); = ios::in); (and "numbers.dat";// sizeof(line)); Inc... file to kill valid our search 24. fault. bound it)? search elements to for (y File search orange n) with in data numbers list main (gdb) run quit y Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 12

13 If at first you don't succeed, play second base. We try again: Enter number to search for or -1 to quit:4 Found at index 0 Found at index 0 Not found Enter number to search for or -1 to quit:^c Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 13

14 % GDB list break Starting Enter Breakpoint (gdb) Found 73 search is66,77 70 number atfree program: index 1, software at tomain 0while 0x249e: search /usr/sdo/search/search () middle if... (1) at for (data[middle] (low break; file high std::cout search.cc:70 { or = == search.cc, = (low -1 middle; high) to + << quit:4 high) "Not < == "Found { line search) found\n"; / 2; at70. index { " << middle << '\n'; run Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 14

15 if std::cout % Found Not Enter program (data[middle] found number runs index << "Found to forever 01 search == search) at(or index foruntil { " -1 << we to middle abort quit: it) << '\n'; The Mistake Changes to: break; Try again: search Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 15

16 % GDB Starting Enter Program 0x2500 $1 $2 print $ (gdb) 67 = is 04 5number search data[middle] free inreceived program: main software to() search signal /usr/sdo/search/search at if middle and search.cc:79 for (low (data[middle] SIGINT,... or = == (low middle; -1 high) Interrupt. to + quit: high) { == < search) / 2; { Debug Session III run ^C 5 (gdb) Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 16

17 $5 $6 $7 $8 $9 print $10 (gdb) The = = program data[0] data[1] 6 is running. middle if (low (data[middle] Quit = == (low middle; anyway high) + high) { < == (and search) / kill 2; it)? { (y or n) Debugging Cont. print low print middle print high print search quit y Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 17

18 Final Fix Should be: if (data[middle] < search) low = middle; else high = middle; if (data[middle] < search) low = middle +1; else high = middle -1; Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 18

19 float // extern if return blue*correction Lookup (point_number point_color(int correction; float lookup(int (red*correction = red,green,blue;// = lookup(point_number); point_number; * == point_number); ) * /* ### color current /* + Temp ### correction code Line colors ### to stop */ factor on ### */ Tricking Interactive Debuggers to Stop when you want them to { green*correction); Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 19

20 Runtime Errors Segmentation Violation Bad pointer Indexing off the end of an array Stack Overflow Too many local variables (big problem in DOS/Windows). Infinite recursion Divide by 0 Floating exception (core dumped) On UNIX this is caused by floating point and integer divides. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 20

21 #include int j std::cout = i,j; 1; 0; / j; <iostream> << /* //"Before "Starting\n"; "After\n"; two divide random divide..."; by zero integers error */ Buffering problem main() { return(0); When run, this program outputs: Starting Floating exception (core dumped) Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 21

22 #include int j std::cout = i,j; 1; 0; / j; <iostream> << /* //"Starting\n"; "Before "After\n"; two divide random divide..."; by zero integers error */ Problem Solved int main() { std::cout.flush(); std::cout.flush(); std::cout.flush(); return(0); Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 22

23 Confessional Method of Debugging Programmer explains his program to an interested party, an uninterested part, a wall. The programmer just explains his program. Typical session: Hey Bill, could you take a look at this. My program has a bug in it. The output should be 8.0 and I m getting The output is computed using this formula and I ve checked out the payment value and rate and the date must be correct unless there is something wrong with the leap year code which Thank you Bill, you ve found my problem. Bill says nothing. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 23

24 Optimization And now a word about optimization: Don t! Getting a faster machine is the most economical way to speed up your program. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 24

25 const void int for matrix[x][y] matrix[x_size][y_size]; x,y; (x (y init_matrix(void) int = 0; // x y = < current -1; X_SIZE; Y_SIZE; = 60; 30; element ++x) ++y) { to initialize Unoptimized Program { Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 25

26 const int void register for matrix[x][y] matrix[x_size][y_size]; (x (y init_matrix(void) int = int 0; x y x,y; = < -1; X_SIZE; Y_SIZE; = 60; 30; // current ++x) ++y) { element to initialize Register Variables { The register keword is a hint that tells the compiter to put a frequently used variable in a machine register (which is faster than stack memory). But most modern compilers ignore this hit because they can do register allocation better than an human anyway. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 26

27 const int void register for matrix[x][y] current matrix[x_size][y_size]; (y (x init_matrix(void) int = int element 0; y x x,y; = < -1; Y_SIZE; X_SIZE; = to60; 30; initialize // ++y) ++x) { With loop ordering { Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 27

28 pro gram must perform the following s: Powers of 2 Indexing an array requires a multiply. For example to execute the line: matrix[x][y] = -1; the program must compute the location for placing the -1. To do this the 1) Get the address of the matrix. 2) Compute x * Y_SIZE. 3) Compute y. 4) Add up all three parts to form the address. In C++ this code looks like: *(matrix + (x * Y_SIZE) + y) = -1; If we change Y_SIZE from 30 to 32, we waste space but speed up the computation. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 28

29 const int void register for *matrix_ptr (index matrix[x_size][y_size]; init_matrix(void) int int = = index; *matrix_ptr; 0; &matrix[0][0]; -1; index = 60; 30; < X_SIZE // element Current * Y_SIZE; counter element ++index) { Using Pointers { ++matrix_ptr; Can the loop counter and the matrix_ptr be combined? Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 29

30 #include const int void memset(matrix, matrix[x_size][y_size]; init_matrix(void) int<string.h> -1, = 60; 30; sizeof(matrix)); Using the library function { Our function is one line long. We might want to make it an inline function. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 30

31 Optimizing techniques Remove invariant code from loops Loop ordering Reduction in strength Use reference parameters Powers of 2 Pointers inline functions Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 31

32 Optimization Costs Operation file input and out ( << and >>) Relative Cost 1000 Also includes the C functions printf and scanf. new and delete 800 trigonometric functions (sin, cos...) 500 floating point (any operation) 100 integer divide 30 integer multiple 20 function call 10 simple array index 6 shifts 5 add/subtract 5 pointer dereference 2 bitwise and, or, not 1 logical and, or, not 1 Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 32

Program Design: Using the Debugger

Program Design: Using the Debugger rogram Design, February 2, 2004 1 Program Design: Using the Debugger A debugger is an alternative to putting print (printf in C) statements in your program, recompiling and trying to find out what values

More information

Chapter - 8 More Control Statements. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

Chapter - 8 More Control Statements. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Chapter - 8 More Control Statements Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 for Statement General form: for (initial-statement; condition; iteration-statement) body-statement;

More information

Chapter 8. More Control Statements

Chapter 8. More Control Statements Chapter 8. More Control Statements 8.1 for Statement The for statement allows the programmer to execute a block of code for a specified number of times. The general form of the for statement is: for (initial-statement;

More information

The Dynamic Debugger gdb

The Dynamic Debugger gdb Introduction The Dynamic Debugger gdb This handout introduces the basics of using gdb, a very powerful dynamic debugging tool. No-one always writes programs that execute perfectly every time, and while

More information

1 A Brief Introduction To GDB

1 A Brief Introduction To GDB 1 A Brief Introduction To GDB GDB, the GNU Project debugger, allows you to see what is going on inside another program while it executes or what another program was doing at the moment it crashed. GDB

More information

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 Lecture 11 gdb and Debugging (Thanks to Hal Perkins)

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 Lecture 11 gdb and Debugging (Thanks to Hal Perkins) CSE 374 Programming Concepts & Tools Brandon Myers Winter 2015 Lecture 11 gdb and Debugging (Thanks to Hal Perkins) Hacker tool of the week (tags) Problem: I want to find the definition of a function or

More information

GDB Linux GNU Linux Distribution. gdb gcc g++ -g gdb EB_01.cpp

GDB Linux GNU Linux Distribution. gdb gcc g++ -g gdb EB_01.cpp B Linux GDB GDB Linux GNU GPL Linux Distribution Linux E-B.1 gcc g++ -g EB_01.cpp EB_01.cpp E/EB/EB_01.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /**** :EB_01.cpp : *****/ #include

More information

Chapter - 7 The Programming Process. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page1

Chapter - 7 The Programming Process. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page1 Chapter - 7 The Programming Process Practical C++ Programming Copyright 2003 O'Reilly and Associates Page1 The Programming Process ## fig needs fixing ## Actually needs rewriting for this format ## Practical

More information

1. Allowed you to see the value of one or more variables, or 2. Indicated where you were in the execution of a program

1. Allowed you to see the value of one or more variables, or 2. Indicated where you were in the execution of a program CS0449 GDB Lab What is a debugger? A debugger is a program that helps you find logical mistakes in your programs by running them in a controlled way. Undoubtedly by this point in your programming life,

More information

Scientific Programming in C IX. Debugging

Scientific Programming in C IX. Debugging Scientific Programming in C IX. Debugging Susi Lehtola 13 November 2012 Debugging Quite often you spend an hour to write a code, and then two hours debugging why it doesn t work properly. Scientific Programming

More information

Programming Studio #9 ECE 190

Programming Studio #9 ECE 190 Programming Studio #9 ECE 190 Programming Studio #9 Concepts: Functions review 2D Arrays GDB Announcements EXAM 3 CONFLICT REQUESTS, ON COMPASS, DUE THIS MONDAY 5PM. NO EXTENSIONS, NO EXCEPTIONS. Functions

More information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 11 gdb and Debugging 1 Administrivia HW4 out now, due next Thursday, Oct. 26, 11 pm: C code and libraries. Some tools: gdb (debugger)

More information

Using a debugger. Segmentation fault? GDB to the rescue!

Using a debugger. Segmentation fault? GDB to the rescue! Using a debugger Segmentation fault? GDB to the rescue! But first... Let's talk about the quiz Let's talk about the previous homework assignment Let's talk about the current homework assignment K findkey(v

More information

Using gdb to find the point of failure

Using gdb to find the point of failure gdb gdb is the GNU debugger on our CS machines. gdb is most effective when it is debugging a program that has debugging symbols linked in to it. With gcc and g++, this is accomplished using the -g option,

More information

GDB Tutorial. University of Waterloo

GDB Tutorial. University of Waterloo GDB Tutorial University of Waterloo Version 1.1 Caroline Kierstead and Peter A. Buhr c 1993 May 1, 2000 Permission is granted to make copies for personal or educational use 2 GDB Tutorial Contents 1 Introduction

More information

Lecture 07 Debugging Programs with GDB

Lecture 07 Debugging Programs with GDB Lecture 07 Debugging Programs with GDB In this lecture What is debugging Most Common Type of errors Process of debugging Examples Further readings Exercises What is Debugging Debugging is the process of

More information

C Program Development and Debugging under Unix SEEM 3460

C Program Development and Debugging under Unix SEEM 3460 C Program Development and Debugging under Unix SEEM 3460 1 C Basic Elements SEEM 3460 2 C - Basic Types Type (32 bit) Smallest Value Largest Value short int -32,768(-2 15 ) 32,767(2 15-1) unsigned short

More information

SU 2017 May 18/23 LAB 3 Bitwise operations, Program structures, Functions (pass-by-value), local vs. global variables. Debuggers

SU 2017 May 18/23 LAB 3 Bitwise operations, Program structures, Functions (pass-by-value), local vs. global variables. Debuggers SU 2017 May 18/23 LAB 3 Bitwise operations, Program structures, Functions (pass-by-value), local vs. global variables. Debuggers 1. Problem A Pass-by-value, and trace a program with debugger 1.1 Specification

More information

CSE 351. GDB Introduction

CSE 351. GDB Introduction CSE 351 GDB Introduction Lab 2 Out either tonight or tomorrow Due April 27 th (you have ~12 days) Reading and understanding x86_64 assembly Debugging and disassembling programs Today: General debugging

More information

CS354 gdb Tutorial Written by Chris Feilbach

CS354 gdb Tutorial Written by Chris Feilbach CS354 gdb Tutorial Written by Chris Feilbach Purpose This tutorial aims to show you the basics of using gdb to debug C programs. gdb is the GNU debugger, and is provided on systems that

More information

CS/COE 0449 term 2174 Lab 5: gdb

CS/COE 0449 term 2174 Lab 5: gdb CS/COE 0449 term 2174 Lab 5: gdb What is a debugger? A debugger is a program that helps you find logical mistakes in your programs by running them in a controlled way. Undoubtedly by this point in your

More information

CMPSC 311- Introduction to Systems Programming Module: Debugging

CMPSC 311- Introduction to Systems Programming Module: Debugging CMPSC 311- Introduction to Systems Programming Module: Debugging Professor Patrick McDaniel Fall 2016 Debugging Often the most complicated and time-consuming part of developing a program is debugging.

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

Debugging. John Lockman Texas Advanced Computing Center

Debugging. John Lockman Texas Advanced Computing Center Debugging John Lockman Texas Advanced Computing Center Debugging Outline GDB Basic use Attaching to a running job DDT Identify MPI problems using Message Queues Catch memory errors PTP For the extremely

More information

CMPSC 311- Introduction to Systems Programming Module: Debugging

CMPSC 311- Introduction to Systems Programming Module: Debugging CMPSC 311- Introduction to Systems Programming Module: Debugging Professor Patrick McDaniel Fall 2014 Debugging Often the most complicated and time-consuming part of developing a program is debugging.

More information

CS3210: Tutorial Session 2. Kyuhong Park-- edited by Kyle Harrigan

CS3210: Tutorial Session 2. Kyuhong Park-- edited by Kyle Harrigan 1 CS3210: Tutorial Session 2 Kyuhong Park-- edited by Kyle Harrigan 2 Overview Goal: Understand C and GDB Part1: C Programming Part2: GDB Part3: In-class Exercises 3 Revised Tutorial Format Recommended

More information

Problem Set 1: Unix Commands 1

Problem Set 1: Unix Commands 1 Problem Set 1: Unix Commands 1 WARNING: IF YOU DO NOT FIND THIS PROBLEM SET TRIVIAL, I WOULD NOT RECOMMEND YOU TAKE THIS OFFERING OF 300 AS YOU DO NOT POSSESS THE REQUISITE BACKGROUND TO PASS THE COURSE.

More information

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory Announcements CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory There will be no lecture on Tuesday, Feb. 16. Prof. Thompson s office hours are canceled for Monday, Feb. 15. Prof.

More information

Arrays and Pointers. CSC209: Software Tools and Systems Programming (Winter 2019) Furkan Alaca & Paul Vrbik. University of Toronto Mississauga

Arrays and Pointers. CSC209: Software Tools and Systems Programming (Winter 2019) Furkan Alaca & Paul Vrbik. University of Toronto Mississauga Arrays and Pointers CSC209: Software Tools and Systems Programming (Winter 2019) Furkan Alaca & Paul Vrbik University of Toronto Mississauga https://mcs.utm.utoronto.ca/~209/ Week 2 Alaca & Vrbik (UTM)

More information

Topic 6: A Quick Intro To C

Topic 6: A Quick Intro To C Topic 6: A Quick Intro To C Assumption: All of you know Java. Much of C syntax is the same. Also: Many of you have used C or C++. Goal for this topic: you can write & run a simple C program basic functions

More information

Intro to Segmentation Fault Handling in Linux. By Khanh Ngo-Duy

Intro to Segmentation Fault Handling in Linux. By Khanh Ngo-Duy Intro to Segmentation Fault Handling in Linux By Khanh Ngo-Duy Khanhnd@elarion.com Seminar What is Segmentation Fault (Segfault) Examples and Screenshots Tips to get Segfault information What is Segmentation

More information

CSE au Midterm Exam Nov. 2, 2018 Sample Solution

CSE au Midterm Exam Nov. 2, 2018 Sample Solution Question 1. (16 points) Build tools and make. We re building a C++ software back-end prototype for a new food web site. So far, we ve got the following source files with the code for two main programs

More information

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

CSci 4061 Introduction to Operating Systems. Programs in C/Unix CSci 4061 Introduction to Operating Systems Programs in C/Unix Today Basic C programming Follow on to recitation Structure of a C program A C program consists of a collection of C functions, structs, arrays,

More information

CS2141 Software Development using C/C++ Debugging

CS2141 Software Development using C/C++ Debugging CS2141 Software Development using C/C++ Debugging Debugging Tips Examine the most recent change Error likely in, or exposed by, code most recently added Developing code incrementally and testing along

More information

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

More information

CSCI0330 Intro Computer Systems Doeppner. Lab 02 - Tools Lab. Due: Sunday, September 23, 2018 at 6:00 PM. 1 Introduction 0.

CSCI0330 Intro Computer Systems Doeppner. Lab 02 - Tools Lab. Due: Sunday, September 23, 2018 at 6:00 PM. 1 Introduction 0. CSCI0330 Intro Computer Systems Doeppner Lab 02 - Tools Lab Due: Sunday, September 23, 2018 at 6:00 PM 1 Introduction 0 2 Assignment 0 3 gdb 1 3.1 Setting a Breakpoint 2 3.2 Setting a Watchpoint on Local

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Chapter - 9 Variable Scope and Functions Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Variable Scope and Class Variables are defined by two attributes: Scope The area where a

More information

Stream States. Formatted I/O

Stream States. Formatted I/O C++ Input and Output * the standard C++ library has a collection of classes that can be used for input and output * most of these classes are based on a stream abstraction, the input or output device is

More information

18-600: Recitation #3

18-600: Recitation #3 18-600: Recitation #3 Bomb Lab & GDB Overview September 12th, 2017 1 Today X86-64 Overview Bomb Lab Introduction GDB Tutorial 2 3 x86-64: Register Conventions Arguments passed in registers: %rdi, %rsi,

More information

GDB Tutorial. University of Waterloo

GDB Tutorial. University of Waterloo GDB Tutorial University of Waterloo Version 1.0 Caroline Kierstead and Peter A. Buhr c 2002 April 1, 2002 Permission is granted to make copies for personal or educational use 2 GDB Tutorial Contents 1

More information

GDB Tutorial. Young W. Lim Tue. Young W. Lim GDB Tutorial Tue 1 / 32

GDB Tutorial. Young W. Lim Tue. Young W. Lim GDB Tutorial Tue 1 / 32 GDB Tutorial Young W. Lim 2017-02-14 Tue Young W. Lim GDB Tutorial 2017-02-14 Tue 1 / 32 Outline 1 Introduction Young W. Lim GDB Tutorial 2017-02-14 Tue 2 / 32 Based on "Self-service Linux: Mastering the

More information

Binghamton University. CS-220 Spring C Debugging Basics. No relevant text

Binghamton University. CS-220 Spring C Debugging Basics. No relevant text C Debugging Basics No relevant text First Computer Bug 2 The printf debugger Insert printf statements to print debug information Build/Run Modify to print new information Advantages Simple Complete Available

More information

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial A Walkthrough with Examples CMSC 212 - Spring 2009 Last modified March 22, 2009 What is gdb? GNU Debugger A debugger for several languages, including C and C++ It allows you to inspect what the program

More information

CSE 410: Systems Programming

CSE 410: Systems Programming CSE 410: Systems Programming Recitation 4: Introduction to gdb Introduction The GNU Debugger, or gdb, is a powerful symbolic debugger. Symbolic debuggers are available for many languages and platforms,

More information

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference

More information

ECE/ME/EMA/CS 759 High Performance Computing for Engineering Applications

ECE/ME/EMA/CS 759 High Performance Computing for Engineering Applications ECE/ME/EMA/CS 759 High Performance Computing for Engineering Applications Elements of Program Debugging Dan Negrut, 2017 ECE/ME/EMA/CS 759 UW-Madison Debugging on Euler [with gdb] Slides on gdb include

More information

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

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet High-performance computing and programming Intro to C on Unix/Linux IT Uppsala universitet What is C? An old imperative language that remains rooted close to the hardware C is relatively small and easy

More information

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

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science Memory Allocation in C C Programming and Software Tools N.C. State Department of Computer Science The Easy Way Java (JVM) automatically allocates and reclaims memory for you, e.g... Removed object is implicitly

More information

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

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

Exercise Session 6 Computer Architecture and Systems Programming

Exercise Session 6 Computer Architecture and Systems Programming Systems Group Department of Computer Science ETH Zürich Exercise Session 6 Computer Architecture and Systems Programming Herbstsemester 2016 Agenda GDB Outlook on assignment 6 GDB The GNU Debugger 3 Debugging..

More information

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

Programs in memory. The layout of memory is roughly:

Programs in memory. The layout of memory is roughly: Memory 1 Programs in memory 2 The layout of memory is roughly: Virtual memory means that memory is allocated in pages or segments, accessed as if adjacent - the platform looks after this, so your program

More information

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265 Parameter passing Programming in C UVic SEng 265 Daniel M. German Department of Computer Science University of Victoria 1 SEng 265 dmgerman@uvic.ca C implements call-by-value parameter passing int a =

More information

C++ Tutorial AM 225. Dan Fortunato

C++ Tutorial AM 225. Dan Fortunato C++ Tutorial AM 225 Dan Fortunato Anatomy of a C++ program A program begins execution in the main() function, which is called automatically when the program is run. Code from external libraries can be

More information

Final CSE 131B Spring 2004

Final CSE 131B Spring 2004 Login name Signature Name Student ID Final CSE 131B Spring 2004 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (25 points) (24 points) (32 points) (24 points) (28 points) (26 points) (22 points)

More information

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging Outline Computer programming Debugging Hints Gathering evidence Common C errors "Education is a progressive discovery of our own ignorance." Will Durant T.U. Cluj-Napoca - Computer Programming - lecture

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

CS102 Software Engineering Principles

CS102 Software Engineering Principles CS102 Software Engineering Principles Bill Cheng http://merlot.usc.edu/cs102-s12 1 Software Engineering Principles You need to develop a plan before you start writing your code Choose the proper data structures

More information

CS61 Lecture II: Data Representation! with Ruth Fong, Stephen Turban and Evan Gastman! Abstract Machines vs. Real Machines!

CS61 Lecture II: Data Representation! with Ruth Fong, Stephen Turban and Evan Gastman! Abstract Machines vs. Real Machines! CS61 Lecture II: Data Representation with Ruth Fong, Stephen Turban and Evan Gastman Abstract Machines vs. Real Machines Abstract machine refers to the meaning of a program in a high level language (i.e.

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

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

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

Unix and C Program Development SEEM

Unix and C Program Development SEEM Unix and C Program Development SEEM 3460 1 Operating Systems A computer system cannot function without an operating system (OS). There are many different operating systems available for PCs, minicomputers,

More information

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. CMPSC11 Final (Study Guide) Fall 11 Prof Hartman Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) This is a collection of statements that performs

More information

C Functions. Object created and destroyed within its block auto: default for local variables

C Functions. Object created and destroyed within its block auto: default for local variables 1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program

More information

Important From Last Time

Important From Last Time Important From Last Time Embedded C Pros and cons Macros and how to avoid them Intrinsics Interrupt syntax Inline assembly Today Advanced C What C programs mean How to create C programs that mean nothing

More information

Data and File Structures Laboratory

Data and File Structures Laboratory Tools: GDB, Valgrind Assistant Professor Machine Intelligence Unit Indian Statistical Institute, Kolkata August, 2018 1 GDB 2 Valgrind A programmer s experience Case I int x = 10, y = 25; x = x++ + y++;

More information

HW1 due Monday by 9:30am Assignment online, submission details to come

HW1 due Monday by 9:30am Assignment online, submission details to come inst.eecs.berkeley.edu/~cs61c CS61CL : Machine Structures Lecture #2 - C Pointers and Arrays Administrivia Buggy Start Lab schedule, lab machines, HW0 due tomorrow in lab 2009-06-24 HW1 due Monday by 9:30am

More information

Review of Scientific Programming in C and Fortran. Michael McLennan Software Architect HUBzero Platform for Scientific Collaboration

Review of Scientific Programming in C and Fortran. Michael McLennan Software Architect HUBzero Platform for Scientific Collaboration Review of Scientific Programming in C and Fortran Michael McLennan Software Architect HUBzero Platform for Scientific Collaboration Monte Carlo Simulator Simulate by randomly generating thousands of tracks?

More information

Page 1. Today. Important From Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right?

Page 1. Today. Important From Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right? Important From Last Time Today Embedded C Pros and cons Macros and how to avoid them Intrinsics Interrupt syntax Inline assembly Advanced C What C programs mean How to create C programs that mean nothing

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to. Refresher When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to. i.e. char *ptr1 = malloc(1); ptr1 + 1; // adds 1 to pointer

More information

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Topic 6: A Quick Intro To C. Reading. goto Considered Harmful History Topic 6: A Quick Intro To C Reading Assumption: All of you know basic Java. Much of C syntax is the same. Also: Some of you have used C or C++. Goal for this topic: you can write & run a simple C program

More information

Important From Last Time

Important From Last Time Important From Last Time Embedded C Ø Pros and cons Macros and how to avoid them Intrinsics Interrupt syntax Inline assembly Today Advanced C What C programs mean How to create C programs that mean nothing

More information

Memory Management: The process by which memory is shared, allocated, and released. Not applicable to cache memory.

Memory Management: The process by which memory is shared, allocated, and released. Not applicable to cache memory. Memory Management Page 1 Memory Management Wednesday, October 27, 2004 4:54 AM Memory Management: The process by which memory is shared, allocated, and released. Not applicable to cache memory. Two kinds

More information

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

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12 Week 9 Part 1 Kyle Dewey Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2 Dynamic Allocation Recall... Dynamic memory allocation allows us to request memory on the fly

More information

War Industries Presents: An Introduction to Programming for Hackers Part III - Advanced Variables & Flow Control.

War Industries Presents: An Introduction to Programming for Hackers Part III - Advanced Variables & Flow Control. War Industries Presents: An Introduction to Programming for Hackers Part III - Advanced Variables & Flow Control By Lovepump, 2004 Visit: www.warindustries.com Part II Programs 101 Goals: At the end of

More information

buffer overflow exploitation

buffer overflow exploitation buffer overflow exploitation Samuele Andreoli, Nicolò Fornari, Giuseppe Vitto May 11, 2016 University of Trento Introduction 1 introduction A Buffer Overflow is an anomaly where a program, while writing

More information

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them. Lab 8 Each lab will begin with a recap of last lab and a brief demonstration by the TAs for the core concepts examined in this lab. As such, this document will not serve to tell you everything the TAs

More information

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017 1. Do a page check: you should have 8 pages including this cover sheet. 2. You have 50 minutes

More information

Lab 8 - Vectors, and Debugging. Directions

Lab 8 - Vectors, and Debugging. Directions Lab 8 - Vectors, and Debugging. Directions The labs are marked based on attendance and effort. It is your responsibility to ensure the TA records your progress by the end of the lab. While completing these

More information

Technical Questions. Q 1) What are the key features in C programming language?

Technical Questions. Q 1) What are the key features in C programming language? Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility

More information

Chapter 1 & 2 Introduction to C Language

Chapter 1 & 2 Introduction to C Language 1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History

More information

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere

More information

Stack overflow exploitation

Stack overflow exploitation Stack overflow exploitation In order to illustrate how the stack overflow exploitation goes I m going to use the following c code: #include #include #include static void

More information

Chapter 14 - Advanced C Topics

Chapter 14 - Advanced C Topics Chapter 14 - Advanced C Topics Outline 14.1 Introduction 14.2 Redirecting Input/Output on UNIX and DOS Systems 14.3 Variable-Length Argument Lists 14.4 Using Command-Line Arguments 14.5 Notes on Compiling

More information

12. Debugging. Overview. COMP1917: Computing 1. Developing Programs. The Programming Cycle. Programming cycle. Do-it-yourself debugging

12. Debugging. Overview. COMP1917: Computing 1. Developing Programs. The Programming Cycle. Programming cycle. Do-it-yourself debugging COMP1917 12s2 Debugging 1 COMP1917: Computing 1 12. Debugging Overview Programming cycle Do-it-yourself debugging Debugging withgdb Nastier bugs Memory leaks COMP1917 12s2 Debugging 2 Developing Programs

More information

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions Topic: File input/output I. Streams II. Access methods III. C++ style Input, output, random access Stream classes: ifstream, ofstream IV. C style The FILE data type Opening files Writing to, reading text

More information

CENG 447/547 Embedded and Real-Time Systems. Review of C coding and Soft Eng Concepts

CENG 447/547 Embedded and Real-Time Systems. Review of C coding and Soft Eng Concepts CENG 447/547 Embedded and Real-Time Systems Review of C coding and Soft Eng Concepts Recall (C-style coding syntax) ; - Indicate the end of an expression {} - Used to delineate when a sequence of elements

More information

Jackson State University Department of Computer Science CSC / Advanced Information Security Spring 2013 Lab Project # 5

Jackson State University Department of Computer Science CSC / Advanced Information Security Spring 2013 Lab Project # 5 Jackson State University Department of Computer Science CSC 439-01/539-02 Advanced Information Security Spring 2013 Lab Project # 5 Use of GNU Debugger (GDB) for Reverse Engineering of C Programs in a

More information

A short session with gdb verifies a few facts; the student has made notes of some observations:

A short session with gdb verifies a few facts; the student has made notes of some observations: This assignment refers to concepts discussed in the course notes on gdb and the book The Art of Debugging by Matloff & Salzman. The questions are definitely "hands-on" and will require some reading beyond

More information

Debugging. ICS312 Machine-Level and Systems Programming. Henri Casanova

Debugging. ICS312 Machine-Level and Systems Programming. Henri Casanova Debugging ICS312 Machine-Level and Systems Programming Henri Casanova (henric@hawaii.edu) Debugging Even when written in high-level languages, programs have bugs Recall the thought that when moving away

More information

CS201 Spring2009 Solved Sunday, 09 May 2010 14:57 MIDTERM EXAMINATION Spring 2009 CS201- Introduction to Programming Question No: 1 ( Marks: 1 ) - Please choose one The function of cin is To display message

More information

Using the Debugger. Michael Jantz Dr. Prasad Kulkarni

Using the Debugger. Michael Jantz Dr. Prasad Kulkarni Using the Debugger Michael Jantz Dr. Prasad Kulkarni 1 Debugger What is it a powerful tool that supports examination of your program during execution. Idea behind debugging programs. Creates additional

More information

Quiz 0 Review Session. October 13th, 2014

Quiz 0 Review Session. October 13th, 2014 Quiz 0 Review Session October 13th, 2014 Topics (non-exhaustive) Binary. ASCII. Algorithms. Pseudocode. Source code. Compiler. Object code. Scratch. Statements. Boolean expressions. Conditions. Loops.

More information

ESC101N: Fundamentals of Computing End-sem st semester

ESC101N: Fundamentals of Computing End-sem st semester ESC101N: Fundamentals of Computing End-sem 2010-11 1st semester Instructor: Arnab Bhattacharya 8:00-11:00am, 15th November, 2010 Instructions 1. Please write your name, roll number and section below. 2.

More information

You can also start with both an executable program and a core file specified:

You can also start with both an executable program and a core file specified: NAME ddd, xddd - the data display debugger SYNOPSIS ddd [ gdb ][ dbx ][ xdb ][ jdb ][ pydb ][ perl ][ debugger name ][ [r]host [username@]hostname ]] [ help ][ trace ][ version ][ configuration ][options...

More information

Simulavr. A simulator for the Atmel AVR family of microcontrollers. For simulavr version , 18 January by Theodore A.

Simulavr. A simulator for the Atmel AVR family of microcontrollers. For simulavr version , 18 January by Theodore A. Simulavr A simulator for the Atmel AVR family of microcontrollers. For simulavr version 0.1.2.5, 18 January 2004. by Theodore A. Roth Send bugs and comments on Simulavr to simulavr-devel@nongnu.org Copyright

More information

General Debugging Strategies

General Debugging Strategies An Interactive Guide to Faster, Less Frustrating Debugging Adapted from http://heather.cs.ucdavis.edu/~matloff/unixandc/clanguage/debug.html by Norman Matloff Contents: Introduction General Debugging Strategies

More information

JTSK Programming in C II C-Lab II. Lecture 3 & 4

JTSK Programming in C II C-Lab II. Lecture 3 & 4 JTSK-320112 Programming in C II C-Lab II Lecture 3 & 4 Xu (Owen) He Spring 2018 Slides modified from Dr. Kinga Lipskoch Planned Syllabus The C Preprocessor Bit Operations Pointers and Arrays (Dynamically

More information