Programming in C First meeting

Similar documents
Programming in C week 1 meeting Tiina Niklander

Programming in C First meeting Tiina Niklander

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

PRINCIPLES OF OPERATING SYSTEMS

CS240: Programming in C

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

ch = argv[i][++j]; /* why does ++j but j++ does not? */

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

CSE 351. Introduction & Course Tools

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

Software Development With Emacs: The Edit-Compile-Debug Cycle

CS 253: Intro to Systems Programming 1/21

Beyond this course. Machine code. Readings: CP:AMA 2.1, 15.4

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

CSE 124 Discussion (10/3) C/C++ Basics

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

Lecture 07 Debugging Programs with GDB

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

CMPT 300. Operating Systems. Brief Intro to UNIX and C

Programming in C Lecture Tiina Niklander

Short Notes of CS201

Recitation: Cache Lab & C

THE UNIVERSITY OF WESTERN ONTARIO. COMPUTER SCIENCE 211a FINAL EXAMINATION 17 DECEMBER HOURS

The C standard library

Final Exam 1 /12 2 /12 3 /10 4 /7 5 /4 6 /10 7 /8 8 /9 9 /8 10 /11 11 /8 12 /10 13 /9 14 /13 15 /10 16 /10 17 /12. Faculty of Computer Science

CS201 - Introduction to Programming Glossary By

Problem Set 1: Unix Commands 1

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

CS 61C: Great Ideas in Computer Architecture Introduction to C

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

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

Programming in C. What is C?... What is C?

CMPUT 201: Practical Programming Methodology. Guohui Lin Department of Computing Science University of Alberta September 2018

CS Basics 15) Compiling a C prog.

CS2141 Software Development using C/C++ Debugging

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Reviewing gcc, make, gdb, and Linux Editors 1

Faculty of Science Final Examination. Computer Science B Introduction to Software Systems

CSCI 2132 Final Exam Solutions

just a ((somewhat) safer) dialect.

COSC Software Engineering. Lecture 16: Managing Memory Managers

CSCI 2132 Software Development. Lecture 29: Dynamic Memory Allocation

Exercise 1: Basic Tools

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

CSE 303, Winter 2006, Final Examination 16 March Please do not turn the page until everyone is ready.

Lecture 03 Bits, Bytes and Data Types

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

CSCI 171 Chapter Outlines

C introduction: part 1

Lectures 5-6: Introduction to C

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

How to learn C? CSCI [4 6]730: A C Refresher or Introduction. Diving In: A Simple C Program 1-hello-word.c

#include <stdio.h> int main() { printf ("hello class\n"); return 0; }

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

Programming in C in a UNIX environment

C & Data Structures syllabus

Intermediate Programming, Spring 2017*

2 Compiling a C program

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

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

CSE 374 Programming Concepts & Tools

Lectures 5-6: Introduction to C

CS240: Programming in C. Lecture 2: Overview

Continue: How do I learn C? C Primer Continued (Makefiles, debugging, and more ) Last Time: A Simple(st) C Program 1-hello-world.c!

Laboratory 1 Semester 1 11/12

CSE 333 Midterm Exam July 24, Name UW ID#

C / C++ Coding Rules

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Introduction to C. CS2023 Winter 2004

High-performance computing and programming I. Introduction to C programming in *NIX

CSE 374 Programming Concepts & Tools

Embedded Software TI2726 B. 3. C tools. Koen Langendoen. Embedded Software Group

We first learn one useful option of gcc. Copy the following C source file to your

Project 1: How to Make One Dollar

Formal Methods for C

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

CSE 333 Midterm Exam 7/29/13

Tutorial 1 C Tutorial: Pointers, Strings, Exec

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

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

Intermediate Programming, Spring 2017*

CS133 C Programming. Instructor: Jialiang Lu Office: Information Center 703

Class Information ANNOUCEMENTS

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Oregon State University School of Electrical Engineering and Computer Science. CS 261 Recitation 2. Spring 2016

Computer Programming. The greatest gift you can give another is the purity of your attention. Richard Moss

Recitation 2/18/2012

Introduction to Supercomputing

EL2310 Scientific Programming

ECE 250 / CS 250 Computer Architecture. C Programming

Recitation: C Review. TA s 20 Feb 2017

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

Student Number: Computer Science 211b Final Examination. 28 April hours

Transcription:

Programming in C First meeting 8.9.2016 Tiina Niklander Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 1

Course structure Weekly exercise deadline on Wednesday, lectures on Thursday Official course page: https://www.cs.helsinki.fi/courses/58127/2016/s/k/1 Course structure is in wiki: https://wiki.helsinki.fi/display/cprogramming2015/ Exercise submission on our own server: http://tmc.mooc.fi/hy use your student ID as your username! Grading based on TMC exercises + Exam!!! Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 2

Course material Use a course book! ONE good C course book is a MUST: Kernighan & Richie: C programming language Müldner : C for Java programmer King: C Programming, A Modern Approach Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 3

Learning goal objectives Language structures, data structures, modules, functions+parameters Files Pointers, structured elements Using properly dynamic and static data structures like tables, lists, queues, stacks, trees (from data structures and algorithms course!) NOTE: No C++ features allowed in exam, pure ANSI C only Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 4

TMC Deadline Wednesdays at 15.30 TMC checks automatically the programming tasks and maintains the list of accepted tasks. On-line tool, so can be used from home or at university Paja times (in B221): - Usually on Mon 14-16 & Tue 13-16, but some exceptions may happen - Check from the official course page Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 5

Exam Programming on paper!!! Fall 2014 exam had 4 questions Calculate averages (function + main + command line parameters/arguments) Personal contacts (create data structure + handling functions write comments, but not all codes) File handling and I/O streams essay Errors and mistakes evaluate an existing program 2,5 hours Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 6

C language C assumes that programmer is intelligent enough to use all of its constructs wisely, and so few things are forbidden. Closely tight with UNIX same original developers Low-level language explicit memory allocation and deallocation! allows operations on the memory addresses and bit-level allows dynamic type changes of variables important concept: POINTER (= memory address) C can be a very useful and elegant tool. People often dismiss C, claiming that it is responsible for a bad coding style. The bad coding style is not the fault of the language, but is controlled (and so caused) by the programmer. Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 7

Xptr DC 0 X DC 12 LOAD R1, =X STORE R1, Xptr LOAD R2, X LOAD R3, @Xptr ; R1 230 ; R2 12 ; R3 12 Addresses and values Xptr=225: memory 230 12345 TITO Variable X s address is 230 (&X) Variable X s value is 12 (X) Pointer Xptr s address is 225 (&Xptr) X=230: Pointer Xptr s value is 230 (Xptr) Address of some data (now the address of X) The value of the integer (*Xptr) that Xptr points to is 12 In C language as: Y = *Xptr; /* value of the location Xptr points to */ 12556 128765 12222 12 12998 Faculty of Science Department of Computer Science 8.9.2016 8

Example program #include<stdio.h> /*Header file of a library*/ int main(int argc, char **argv) /* The main function */ { int x, *y, z; /*Variable Declaration*/ if ( (y = malloc (sizeof(int)) ==NULL) return(1); x = 5; *y = 10; z=x+*y; printf ("The sum is %d", z); free(y); return (0); /* standard return value for success */ } Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 9

Compiling: gcc -ansi -pedantic -Wall int main (void) { printf( Hello world \n ); return 0; } Options Wall and pedantic show all possible warnings (used by TMC) Option ansi makes sure that the compiler follows standard (some differences in gcc exist) gcc -ansi -pedantic -Wall -o helloworld helloworld.c /home/fs/niklande/c-luennot/esimerkit/helloworld.c: In function `main': /home/fs/niklande/c-luennot/esimerkit/helloworld.c:3: warning: implicit declaration of function `printf' Faculty of Science Department of Computer Science #include <stdio.h> int main (void) { printf( Hello world \n ); return 0; } www.cs.helsinki.fi 8.9.2016 10

Multiple modules (separate source files with headers) /* main.c */ #include <stdio.h> #include eka.h #include toka.h int main (void) { eka(); toka (); return 0; } /* eka.c */ #include <stdio.h> #include eka.h void eka (void) { puts( eka ); } /* eka.h */ /* toka.c */ #include <stdio.h> #include toka.h void toka (void) { puts( toka ); } /* toka.h */ Could write everytime: void eka (void); gcc c main.c gcc c eka.c gcc c toka.c gcc o ohjelma main.o eka.o toka.o Faculty of Science Department of Computer Science void toka (void); www.cs.helsinki.fi Instead, use makefile 8.9.2016 11

makefile gcc c main.c gcc c eka.c gcc c toka.c gcc o ohjelma main.o eka.o toka.o Create makefile once, use it multiple times make NOTE: tab, not spaces # makefile CC = gcc ansi pedantic Wall ohjelma: main.o eka.o toka.o $(CC) o ohjelma main.o eka.o toka.o eka.o: eka.c eka.h $(CC) c eka.c toka.o: toka.c toka.h $(CC) c toka.c main.o: main.c eka.h toka.h $(CC) c main.c www.cs.helsinki.fi

Modular programming in C C does not support objects or modular programming, but it has features that can be used to mimic them - Functions and function prototypes - Header files Using these features you can separate the interface and implementation *.c hidden implementation *.h public interface Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 13

Structuring a small C program: order of elements in the file #include directive to use (standard) libraries and header files Defining constants and types Easy to locate, modify and control Function prototypes (before the function in used) Function main (every program has one) execution starts here and ends when the main returns. Function definitions (=code of the function) Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 14

What if you have a larger project? - Split to multiple files and libraries main sub1 sub2 sub3 sub4 subsub1 subsub2 subsub2 Functions of standard libraries Modularity at the function level Programmers own libraries of functions Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.201615

Standard libraries Each library contains a set of useful functions A header file gives the function signatures and type definitions for that particular library stdio.h math.h assert.h is usually always used, since it contains the functions for reading and writing contains mathematical functions macro assert to help locate mistakes 29 header files in total (see wikipedia for the list) Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 16

Comparison of C and Java from Müldner: C for java programmers uprimitive data types: character, integer, and real. In C, they are of different sizes, there is no Unicode 16-bit character set ustructured data types: arrays, structures and unions. In C, arrays are static there are no classes ucontrol structures are similar ufunctions are similar www.cs.helsinki.fi

Comparison of C and Java ujava references are called pointers in C. ujava constructs missing in C (ANSI): packages threads exception handling garbage collection standard Graphical User Interface (GUI) built-in definition of a string standard support for networking support for program safety. www.cs.helsinki.fi

Programming style Write clear and easily understandable code (Java programming course style is good!) Cryptic and concise code has no value itself, the clarity is more important do { if (scanf( %d, &i)!=1 i == SENTINEL) break; if (i>maxi) maxi = i; } while (1); void show (char *p) { char *q; printf( [ ); for (q=p; *q!= \0 ; q++) printf( %c, *q); printf( ]\n ); } www.cs.helsinki.fi

What do the following sentences do? while (*q++ = *p++); if ((c=fgetc(filehandle)) == EOF) for (i=a, j=b; i<=j; i += 2, j += 2) www.cs.helsinki.fi

Macro Function calls Function ends #include<stdio.h> #include<string.h> #define SUCCESS 0 #define FAILURE -1 int main(void) { char pass_buff[50] = {0}; printf("\n Enter the password..."); //Get the password from user fgets(pass_buff,sizeof(pass_buff)-1,stdin); //Make sure that the extra(last) character //picked up from stdin is washed off } } //from buffer. pass_buff[strlen(pass_buff)-1] = '\0'; if(! (strcmp(pass_buff,"linux"))) { // Passwords match printf("\n Passwords Match..SUCCESS\n"); return SUCCESS; } else { // Passwords do not macth printf("\n Passwords do not match...failure\n"); return FAILURE; Faculty of Science Department of Computer Science Another example Emply lines would make it more readable Main function From: mylinuxbook.com Array = continuous memory area (here string) 8.9.2016 21

Programming in C Command-line interface needs only shell, no graphical interface the old fashioned way most UNIX experts still do it this way explicit compilation and linking Integrated Development Environments (IDEs) TMC is integrated with NetBeans Eclipse is another very popular one Program still needs to be compiled and linked before execution IDE might hide these phases Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 22

Development process with command-line interface Write program Using suitable editor (vim, nano, emacs,...) Must produce plain text file Compile Link Select the correct compiler and arguments (gcc -c) Link the compiled modules to form a program (gcc) Execute Executing or running the program www.cs.helsinki.fi

Compiling (short program, all in one file) Compile gcc helloworld.c or gcc o helloworld \ helloworld.c Compiler does preprocessing, actual compilation and linking... and produces the executable file a.out or int main (void) { printf( Hello world \n ); return 0; } helloworld www.cs.helsinki.fi

gcc --help Usage: gcc [options] file... Option -- help lists all possible options and features of the compiler, there are plenty -c compile and assemble, but do not link -o <file> place the output into <file> www.cs.helsinki.fi

Program has multiple files and modules Every program file is compiled separately to create object module (or library) gcc c main.c The modules are then linked together to form the complete program gcc o program main.o eka.o toka.o Usually compiled with make (executes a sequence of commands) www.cs.helsinki.fi

After compiling and linking? We have executable program, but does it work? Try to execute it and test the program Look for errors, locate mistakes - Extra print statements - Read the code, simulate execution, THINK! - Use debugger Write automated tests, evaluate test coverage ( -> course: Software testing) On this course we are satisfied with smoke testing or sanity check. (Program seems to satisfy the desciption.) www.cs.helsinki.fi

Testing Target: find mistakes Covers wide spectrum of possible input values Can be automated (using scripts or special test tools/packages) Not part of the learning goals of this course On this course (smoke test, sanity check) usually enough to check - Correct and incorrect input values - Boundary values(-1,0,1) www.cs.helsinki.fi

Extra print statements #ifdef EXTRAPRINT printf ( Fname: Variable name %d \n, variable); #endif Target: try to understand the functionality of the code. Placed: around the most probably mistake location Usually more handy than debugger, if you have an idea of the error location in advance. gcc D EXTRAPRINT www.cs.helsinki.fi

More advanced tools : assert and valgrind assert macro (in assert.h) helps to check the values of variables same code can be compiled with and without the assert checks Write the asserts in the source code (*.c file) memcheck from valgrind makes it possible to find incorrect memory usage used in some of the acceptance tests run at the tmc server used at run time, execute program within valgrind Faculty of Science Department of Computer Science www.cs.helsinki.fi 8.9.2016 30

Debugger gdb (gdb) help List of classes of commands: aliases -- Aliases of other commands breakpoints -- Making program stop at certain points data -- Examining data files -- Specifying and examining files internals -- Maintenance commands obscure -- Obscure features running -- Running the program stack -- Examining the stack status -- Status inquiries support -- Support facilities tracepoints -- Tracing of program execution without stopping the program user-defined -- User-defined commands www.cs.helsinki.fi

core dump Crashed program usually produces a file (code dump) that contains state of the memory and registers at the time of crash. This file can be accessed by debugger to find out values of variable and the location of the instruction that crashed the program. This is not covered on the course, but could be very useful to study at some point. www.cs.helsinki.fi