C No Evil. A practitioner's guide. Copyright : University of Illinois CS 241 Staff

Similar documents
As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

2 ASCII TABLE (DOS) 3 ASCII TABLE (Window)

Pemrograman Dasar. Basic Elements Of Java

The programming language C. sws1 1

Sources: On the Web: Slides will be available on:

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Informatica e Sistemi in Tempo Reale

Stacks. Linear data structures

Chapter 2: Elements of Java

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

C++ Language Tutorial

So far we have considered only numeric processing, i.e. processing of numeric data represented

Programming Microcontrollers in C

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

CS 106 Introduction to Computer Science I

Secrets of printf. 1 Background. 2 Simple Printing. Professor Don Colton. Brigham Young University Hawaii. 2.1 Naturally Special Characters

Variables, Constants, and Data Types

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

First Bytes Programming Lab 2

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

An Incomplete C++ Primer. University of Wyoming MA 5310

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

A list of data types appears at the bottom of this document. String datetimestamp = new java.sql.timestamp(system.currenttimemillis()).

5 Arrays and Pointers

C++ Essentials. Sharam Hekmat PragSoft Corporation

Stack Overflows. Mitchell Adair

Java programming for C/C++ developers

C++ INTERVIEW QUESTIONS

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

DNA Data and Program Representation. Alexandre David

The C Programming Language course syllabus associate level

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

10CS35: Data Structures Using C

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Embedded C Programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Lecture 22: C Programming 4 Embedded Systems

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Member Functions of the istream Class

Introduction to Java

Project 2: Bejeweled

Software Vulnerabilities

Tutorial on C Language Programming

Data Storage: Each time you create a variable in memory, a certain amount of memory is allocated for that variable based on its data type (or class).

Number Representation

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Objective-C Tutorial

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

1 Abstract Data Types Information Hiding

Java Interview Questions and Answers

Channel Access Client Programming. Andrew Johnson Computer Scientist, AES-SSG

SQLITE C/C++ TUTORIAL

arrays C Programming Language - Arrays

How To Write Portable Programs In C

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

64-Bit NASM Notes. Invoking 64-Bit NASM

The Answer to the 14 Most Frequently Asked Modbus Questions

/* File: blkcopy.c. size_t n

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

System Calls Related to File Manipulation

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

TivaWare Utilities Library

Simple Image File Formats

An Implementation of a Tool to Detect Vulnerabilities in Coding C and C++

Lecture 5: Java Fundamentals III

Comp151. Definitions & Declarations

Introduction to Data Structures

Base Conversion written by Cathy Saxton

How To Understand How A Process Works In Unix (Shell) (Shell Shell) (Program) (Unix) (For A Non-Program) And (Shell).Orgode) (Powerpoint) (Permanent) (Processes

Outline Basic concepts of Python language

Object Oriented Software Design II

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

A C Test: The 0x10 Best Questions for Would-be Embedded Programmers

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

SYMETRIX SOLUTIONS: TECH TIP August 2015

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Chapter 7D The Java Virtual Machine

Programming languages C

C++ Programming Language

Programming in C an introduction

Illustration 1: Diagram of program function and data flow

Chapter 4: Computer Codes

Lexical Analysis and Scanning. Honors Compilers Feb 5 th 2001 Robert Dewar

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

7.1 Our Current Model

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

System Calls and Standard I/O

Transcription:

C No Evil A practitioner's guide 1

Topics Program arguments Pointer arithmetic Output Stack memory 2

main() int main(int argc, char** argv) int main(int argc, char* argv[]) 3

main() $ mine c 10 2.0 4

ARGCount ARGValues argv[ ] [0] m i n e \0 [1] [2] - c 1 0 \0 \0 [3] 2. 0 \0 [4] NULL What is argc? 5

Type questions char **argv; What type is argv? What type is *argv? What type is **argv? 6

Review main(int argc, char**argv) { what is *argv? what is argv[argc]? 7

ARGCount ARGValues int main(argc, char** argv) int main(argc, char* argv[]) argc Argument count The number of arguments that are passed to main in the argument vector argv. the value of argc is always one greater than the number of command-line arguments that the user enters. 8

ARGCount ARGValues int main(argc, char** argv) int main(argc, char* argv[]) argv argument vector An array of string pointers passed to a C program's main function argv[0] is always the name of the command argv[argc] is a null pointer 9

Adding integers to pointers Compiler uses the type information long *p; p [long][long][long][...] array of long types What address is p + 2? p + sizeof(long) * 2 10

Output char *s1 = "Hello"; char *s2 = "World"; fprintf(stdout, "%s %s", s1, s2); printf("%s %s", s1, s2); 11

printf Format Identifiers %d or %i Decimal signed integer %o Octal integer %x or %X Hex integer %u Unsigned integer %c Character %s String %f or %g Double %p Pointer All of the parameters should be the value to be inserted EXCEPT %s, this expects a pointer to be passed 12

printf Formatting %[flags][width][.precision][length]specifier %02ld = % 0 2 l d 0 := Zero-fill empty space 2 := Write at least two digits Data type is long =: l Data type is integer =: d 13

printf Basic Data Types #include <stdio.h> // for printf int main(int argc, char *argv[]) { // print "the date is: 01/25/2010", // i.e. 2- or 4-digit with leading zeros // using 32-bit 'long' datatype long day = 25; long month = 1; long year = 2010; printf("the date is: %02ld/%02ld/%04ld\n", month, day, year); // - print 8-digit hex value // - print a pointer value unsigned long ulid = 0x12345678; unsigned long *pid = &ulid; printf("hex value: 0x%02lX at address: %p\n", ulid, pid); 14

printf Basic Data Types // - print 4 bytes of a 32-bit ulong value // as separate hex values unsigned char uc1 = (unsigned char)(ulid >> 24); unsigned char uc2 = (unsigned char)(ulid >> 16); unsigned char uc3 = (unsigned char)(ulid >> 8); unsigned char uc4 = (unsigned char)(ulid >> 0); printf("hex bytes: %02X %02X %02X %02X\n",uc1,uc2,uc3,uc4); // - print double value like "70.35000" double dtemp = 70.35; printf("temperature: %5.5f\n", dtemp); 15

printf Escape Sequences \a <bell> \b <backspace> \e <escape> \f <form-feed> \n <new-line> \r <carriage return> \t <tab> \v <vertical tab> \0 <null> \" <double quote> \\ <backslash> \num an 8-bit character with ASCII value of the 1-, 2-, or 3-digit octal number num. %% <percent> 16

Typecasting C allows programmers to perform typecasting by Place the type name in parentheses and place this in front of the value main() { float a; a = (float)5 / 3; Result is a = 1.666666 Integer 5 is converted to floating point value before division and the operation between float and integer results in float What would a be without the (float)? 17

Typecasting Take care about using typecast If used incorrectly, may result in loss of data e.g., truncating a float when casting to an int 18

Common Pitfall Returning a variable in stack memory from a function What is stack memory? 19

Sample layout for program image in main memory High address Command-line arguments and environment variables stack argc, argv, environment Activation record for function calls (return address, parameters, saved registers, automatic variables) Low address heap Uninitialized static data Initialized static data Program text Allocations from malloc family Processes have three segments: text, data, stack 20

Example int b() { /* */ int a() { /* */ b(); int main(int argc, char **argv) { /* */ a(); 21

Example int b() { /* */ int a() { /* */ b(); Stack Memory: b() int main(int argc, char **argv) { /* */ a(); a() main() 22

Example int b() { /* */ int a() { /* */ b(); Stack Memory: b() int main(int argc, char **argv) { /* */ a(); a() main() 23

Better Example my_queue * b() { my_queue q; return &q; int main(int argc, char **argv) { int myval = 3; a(myval); int a(int yourval) { int myval; my_queue *myqueue; myval = yourval + 3; myqueue = b(); return remove_int(myqueue); main() still calls a() a() still calls b() b() returns a pointer to a() a() returns an int to main() my_queue is a custom struct 24

my_queue * b() { my_queue q; return &q; int a(int yourval) { int myval; my_queue *myqueue; myval = yourval + 3; myqueue = b(); return remove_int(myqueue); void main() { int myval = 3; a(myval); 25

Better Example my_queue * b() { my_queue q; return &q; int a(int yourval) { int myval; my_queue *myqueue; myval = yourval + 3; myqueue = b(); return remove_int(myqueue); int main(int argc, char q (? **argv) bytes) { int myval = 3; a(myval); *myqueue (8 bytes) myval (4 bytes) 6 yourval(4 bytes) myval (4 bytes) 3 **argv (8 bytes) argc (4 bytes) (struct data) 0x 3 0x 1 26

Use your stack wisely Returning a pointer to a stack variable results in unpredictable behavior Three common fixes Good: Pass in a pointer to the variable you want to use Good: Use a heap variable Very Bad (usually): Use a global variable 27