(language, compilation and debugging) David 09/16/2011.

Slides:



Advertisements
Similar presentations
Compilation and Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
Advertisements

C Tutorial Ross Shaull cs146a Why C Standard systems language – Historical reasons (OS have historically been written in C, so libraries written.
C Programming - Lecture 5
Miguel Garzon CrUise Lab - SITE. #include dynamic memory allocationdynamic memory allocation Input/output String handlingString handling Mathematical.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
CS 211 Recitation 1 TA: Ishani Chakraborty. Admin stuff Office hours: 5:00-6:00 pm, Tuesdays at Core.
Unix Continuum of Tools Do something once: use the command line Do something many times: –Use an alias –Use a shell script Do something that is complex.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
C Primer CAS CS210 Ying Ye Boston University. Outline Hello, world Basics in C Comparison of C and Java.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
CPSC 441 Tutorial TA: Fang Wang Introduction to C.
Computer Science 210 Computer Organization 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.
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 Tutorial – Part I CS Introduction to Operating Systems.
Programming With C.
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.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
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.
CSE 232: C++ debugging in Visual Studio and emacs C++ Debugging (in Visual Studio and emacs) We’ve looked at programs from a text-based mode –Shell commands.
CSE 332: C++ debugging Why Debug a Program? When your program crashes –Finding out where it crashed –Examining program memory at that point When a bug.
Week 2-3 Control flow (review) Conditional statements If, else, else if, switch-case, break Loop constructs for, while, do-while, break, continue, label--go;
Introduction to C For the participants of Practical Course „Scientific Computing and Visualization“
C By Example 1 The assumption is that you know Java and need to extend that knowledge so you can program in C. 1. Hello world 2. declarations 3. pass by.
CS 261 – Recitation 2 Fall 2013 Oregon State University School of Electrical Engineering and Computer Science.
C/C++ Basics. Basic Concepts Basic functions of each language: Input, output, math, decision, repetition Types of errors: Syntax errors, logic errors,
Data Display Debugger (DDD)
1 Functions  A function is a named, independent section of C++ code that performs a specific task and optionally returns a value to the calling program.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
1 CS503: Operating Systems Spring 2014 Part 0: Program Structure Dongyan Xu Department of Computer Science Purdue University.
C LANGUAGE Characteristics of C · Small size
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CS252: Systems Programming Ninghui Li Based on Slides by Gustavo Rodriguez-Rivera Topic 2: Program Structure and Using GDB.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
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.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
Lecture 3 Translation.
Stack and Heap Memory Stack resident variables include:
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Function: Declaration
Computer Science 210 Computer Organization
C/C++ Tutorial.
C Primer.
A bit of C programming Lecture 3 Uli Raich.
C Programming Tutorial – Part I
Functions Separate Compilation
CSE 351 Section 1: HW 0 + Intro to C
C Short Overview Lembit Jürimägi.
C programming language
Command-Line Arguments
C Basics.
Computer Systems and Networks
Computer Science 210 Computer Organization
Chapter 14 - Advanced C Topics
Govt. Polytechnic,Dhangar
C/C++ Basics.
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.
Introduction to C Topics Compilation Using the gcc Compiler
When your program crashes
Introduction to C Topics Compilation Using the gcc Compiler
C By Example The assumption is that you know Java and need to extend that knowledge so you can program in C. 1. Hello world 2. declarations 3. pass.
Makefiles, GDB, Valgrind
15213 C Primer 17 September 2002.
C Tutorial Adapted from Wei Qian’s C tutorial slides.
Presentation transcript:

(language, compilation and debugging) David 09/16/2011

Content  C language overview  Compilation  debugging

Basic data type  Integer int, short, long, long long and unsigned  Char a byte has the same number of bits of char  _Bool Integer with 1 bit in memory  Floating point float, double, and long double

Other data type  Pointer type *p; store the address of memory location  array type name[dim];  struct struct ex{ int a; char b;};  const int * const p; /*a const pointer to a int*/ const int * p; /*a pointer to a const int*/

Statement  conditionals if switch-case  loops while (do-while)  while(1){} for  break/continue change the flow of execution

Functions  functions written by yourself return-type function-name ( argument-list-if-necessary ) {...local-declarations......statements... return return-value; }  library functions include header files in your code  libraries stdio.h string.h stdlib.h

Example - 1 int max(int a, int b) { if(a > b) return a; else return b; } int factorial(int a) { int ret = 1; if(a < 0) return -1; while(a > 0) ret *= a--; return ret; }  If and while statements

Example - 2 int even_sum (int m) { int sum = 0; while (m > 0) { switch (m%2) { case 1: m--; break; case 0: sum += m--; } return sum; }  switch statement

Example - 3 float thres_sum(float *array, int size, float thres){ int i; float sum = 0; for(i = 0; i < size; i++) { if(array[i] <= thres) continue; else sum += array[i]; } return sum; }  for statement and pointer

Example - 4 #define PI typedef struct cylinder Cy; Cy max_volumn (Cy cy1, Cy cy2) { float vol1, vol2; vol1 = PI * cy1.r * cy1.r * cy1.H; vol2 = PI * cy2.r * cy2.r * cy2.H; if(vol1 > vol2) return cy1; else return cy2; }  Struct and typedef struct cylinder { float r; float H; };

Recursive function call  a function that contains a call to itself. Divide complex problem into identical simple cases. Must have at least one exit condition that can be satisfied. i.e. Towers of Hanoi int factorial (int n) { if(n == 1) return 1; else return n * factorial(n-1); }

Pass by value vs. pass by address  How are parameters passed to a function? pass by value: make a copy of the variable  Simple  Can not change the passed variable pass by address: address of the variable is passed  Efficient  Can change the variable, though the address of the variable is not changed

void swap1(int a, int b) { int c; c = b; b = a; a = c; } void swap2(int *a, int *b) { int c; c = *b; *b = *a; *a = c; } Example - 5  Pass by value and pass by reference

int main() { int a = 3, b = 5; swap1(a,b); printf(“a is %d, b is %d\n”, a, b); swap2(&a, &b); printf(“a is %d, b is %d\n”, a, b); return 0; } Example - 5 (continued)  Pass by value and pass by reference

Dynamic memory allocation  Typical variable definition (known size) Statically defined in program Allocated in the stack i.e., int a[10]  Define a variable that has a varying size? Allocated at run-time, in the heap Use malloc() function call to allocate Use free(*pointer) to free the memory of a variable

int main() { int *array, i, size; printf(“Input the array size:”); scanf(“%d”, &size); array = (int *)malloc(size, sizeof(int)); for(i=0; i < size; i++) array[i] = i; free(array); //otherwise, memory leak return 0; } Example - 6  Dynamic memory allocation

Preprocessing directives  #define Defines a macro.  #include Inserts text from another source file.  #ifdef Conditionally includes source text if a macro name is defined.  #ifndef Conditionally includes source text if a macro name is not defined. #ifndef FILENAME_H #define FILENAME_H … #endif  #else Conditionally includes source text if the previous #ifdef, #ifndef test fails.  #endif Ends conditional text.

I/O capability  FILE *fp;  fp = fopen(name, mode);  fclose(fp);  fprintf(fp, "format string", variable list);  fgets(str_name, length, fp);  feof(fp); while(!feof(fp)) { fgets(line, max_length, fp); … }

Example - 7 int print_triangle(char style, int base, char *filename) { int i,j; FILE *fp = fopen(filename, “w+”); // open file if(fp == NULL) return -1; if(lines % 2 == 0) base--; for(i = 1; i <= base; i=i+2) { for(j = 0; j < (base – 1) / 2; j++) fprintf(fp, ‘ ‘); for(j = 0; j < i; j++) fprintf(fp, “%c”,style); fprintf(fp, “\n”); } fclose(fp); return 0; } * *** ***** ******* **********  File operations

Command-line arguments  main(int argc, char** argv)  a.out -i 2 -g -x 3  argc = 6 argv[0] = "a.out" argv[1] = "-i" argv[2] = "2" argv[3] = "-g" argv[4] = "-x" argv[5] = "3"

Compilation  gcc codename –o programname  make prog = cc –o prog prog.c  options -o filename -g produce extra debugging information -O(0/1/2/3) optimization level -I(i)directory add header file directory -l(L)libraryname link the library

Example - 8 #include int main() { double s3 = sqrt(3); printf(“Square root of 3 is:%lf\n”, s3); return 0; }  Library Usage  Source code: example.c  Compilation gcc –g –o example example.c –lm

Makefile  Multiple files compilation  files main.c factorial.c hello.c  Run make #Makefile_example all: hello hello: main.o factorial.o hello.o gcc main.o factorial.o hello.o -o hello main.o: main.c gcc -c main.c factorial.o: factorial.c gcc -c factorial.c hello.o: hello.c gcc -c hello.c clean: rm -rf *o hello

Another makefile CC=gcc CFLAGS=-c -Wall SOURCES=main.c hello.c factorial.c OBJECTS=$(SOURCES:.c=.o) EXECUTABLE=hello all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(OBJECTS) -o $(CC) $(CFLAGS) $< -o 

Common compilation errors  Typos (C language is case sensitive)  Try to use a variable without definition  Some statements are not ended by ;  Brackets are not paired ( ), { }, [ ]  Number or type of parameters passed to a function does not match the function definition.  Still have errors? copy the error message, Google it.

gdb for debugging  -g in compilation to enable gdb  gdb obj //start gdb with obj program  (gdb) run (arg )  (gdb) s for step execution  (gdb) p for print variables  (gdb) br to set breakpoint  (gdb) set to modify registers or memory set $eax=10  (gdb) help

Most powerful debug tool  printf function print out check points near vulnerable codes to trace down where bug appears  i.e, File operation, control statements... print out value of variables to trace down when bug happens  i.e. invalid array operation, loop does not stop, and etc.

For more information    Google