Common Errors in C. David Chisnall. February 15, 2011

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

8.5. <summary> Cppcheck addons Using Cppcheck addons Where to find some Cppcheck addons

Semantic Analysis: Types and Type Checking

The C Programming Language course syllabus associate level

arrays C Programming Language - Arrays

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

1 Abstract Data Types Information Hiding

C++ INTERVIEW QUESTIONS

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

The programming language C. sws1 1

A deeper look at Inline functions

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

C Interview Questions

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

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

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

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

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

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

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

5 Arrays and Pointers

Module 816. File Management in C. M. Campbell 1993 Deakin University

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

Chapter 5 Names, Bindings, Type Checking, and Scopes

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

ECS 165B: Database System Implementa6on Lecture 2

Java Interview Questions and Answers

Introduction to Python

public static void main(string[] args) { System.out.println("hello, world"); } }

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Stacks. Linear data structures

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

Illustration 1: Diagram of program function and data flow

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

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

Lecture 9. Semantic Analysis Scoping and Symbol Table

Object Oriented Software Design

Tutorial on C Language Programming

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

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

Introduction to Information Security

Object Oriented Software Design

Informatica e Sistemi in Tempo Reale

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

Object Oriented Software Design II

General Software Development Standards and Guidelines Version 3.5

Chapter 7D The Java Virtual Machine

The Function Pointer

C++FA 3.1 OPTIMIZING C++

MULTIPLICATION AND DIVISION OF REAL NUMBERS In this section we will complete the study of the four basic operations with real numbers.

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

Introduction to Java

X86-64 Architecture Guide

Jonathan Worthington Scarborough Linux User Group

sqlite driver manual

DNA Data and Program Representation. Alexandre David

Section 4.1 Rules of Exponents

C++ Programming Language

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

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

Habanero Extreme Scale Software Research Project

Simple C Programs. Goals for this Lecture. Help you learn about:

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

Chapter 13 Storage classes

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Lecture 2. Binary and Hexadecimal Numbers

csce4313 Programming Languages Scanner (pass/fail)

Embedded C Programming, Linux, and Vxworks. Synopsis

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

Lab Experience 17. Programming Language Translation

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

Technical Writing - Definition of Bad and Good Code

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

03 - Lexical Analysis

Programming Languages CIS 443

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

Parallel and Distributed Computing Programming Assignment 1

10CS35: Data Structures Using C

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Application Note C++ Debugging

CS 241 Data Organization Coding Standards

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

A single register, called the accumulator, stores the. operand before the operation, and stores the result. Add y # add y from memory to the acc

C# and Other Languages

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Lecture 22: C Programming 4 Embedded Systems

Crash Course in Java

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.

Java Types and Enums. Nathaniel Osgood MIT April 25, 2012

Format string exploitation on windows Using Immunity Debugger / Python. By Abysssec Inc

3.GETTING STARTED WITH ORACLE8i

Simplifying Algebraic Fractions

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

Programing the Microprocessor in C Microprocessor System Design and Interfacing ECE 362

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Transcription:

Common Errors in C David Chisnall February 15, 2011

The C Preprocessor Runs before parsing Allows some metaprogramming

Preprocessor Macros Are Not Functions The preprocessor performs token substitution It is completely unaware of the language semantics # define ANSWER 42 test ( ANSWER ); // replaced by test ( 42) # define CALL (x) (x)() CALL (y()); // replaced by (y())()

Example Failure # define MIN (x, y) ((x<y)? x : y) Looks correct? What happens if the arguments are side effects?

Side Effects Evaluated Twice int min = MIN (a(), b()); // Expands to: int min = ((a() <b())? a() : b()); Whichever function has the lower value is called twice If it has side effects, this is very bad If it doesn t, it s still overhead

Solution: Use Functions? int min ( int x, int y) { if (x<y) { return x; } return y; }... min (a(), b()); Looks safe - functions are called then the result passed as arguments. What happens if a() and b() return floats?

Solution 2: More Complex Macro # define MIN (x, y) ({ \ typeof (x) _x = x;\ typeof (y) _y = y;\ _x < _y? _x : y;\ }) Works correctly But uses two GCC-specific extensions It is not possible to portably solve this problem in C99!

Type Promotion Arithmetic results in C depend on the types of the operands This may not do what you want! int64_ t multiply_ extend ( int32_ t a, int32_ t b) { // Wrong! int64_t result = a*b; // Correct : result = ( int64_t )a*b; return result ; }

The Rules (Simplified) Arithmetic operations on the same type evaluate to that type Arithmetic operations on different types use the one with the wider range The actual rules are more complex than this! If you re confused, explicitly cast both arguments. Overly verbose code is better than buggy code double half = 1/ 2; // Evaluates to 0!

Assignment Instead of Comparison if (a = b) What does this do? Assigns b to a Tests if a is zero Enters the if block if it is non-zero

Avoiding Accidental Assignment Put rvalue on the left side of comparions (e.g. 0 == a not a == 0) Explicitly add 0 == when you want to compare against 0. Turn on compiler warnings......and pay attention to them!

Forgetting How Switch Statements Work switch ( expression ) { case 1: dosomething (); case 2: dosomethingelse (); default : giveup (); } Looks right? giveup() is called in all cases dosomethingelse() is called even for values of 1 Sometimes you want this, but usually you don t

Forgetting How Switch Statements Work switch ( expression ) { case 1: dosomething (); break ; case 2: dosomethingelse (); break ; default : giveup (); } This version is right Note for C# programmers: C# switch statement works differently!

Comparing Strings with == if (" test " == a) Why is this wrong? C does not have real strings It uses pointers to characters / character arrays instead This compares two pointers - they are only the same if they point to the same string, not two identical strings in different places in memory

Correct String Comparison if (( NULL!= a) && ( strcmp (" test ", a) == 0)) NULL test is required because strcmp() expects valid pointers The strcmp() function returns an ordering, so you can compare against zero to sort strings

Arrays Are Pointers - Mostly int example ( void ) { char *a = " foo "; char b[] = " foo ";... Are these two the same? "foo" is a global constant string a is a pointer to that string b is a copy of that string on the stack

Printf and Scanf Problems int a = 12; printf (" Current value : %f, old value : %d\n", a); scanf ("%d", a); Three bugs here, what are they? a is passed as the first argument to printf, but the format specifier tells it to expect a floating point value. One of the arguments to printf is missing scanf reads values, so expects pointer arguments These functions expect variable arguments, so the compiler needs special logic to check them. Most compilers will check arguments to these functions, don t ignore the warnings!

More Variadic Function Problems expects_null_terminated (a, b, c, d, e, 0); What s wrong here? Hint: It will work correctly on most platforms. 0 is passed as an int On some platforms, int is 4 bytes, pointers are 8 bytes The callee will read 8 bytes, test if they re NULL and treat them as a pointer if they re not. Bigger problem in C++ because standard C++ has no proper NULL (fixed in C++0X)

Not Understanding Strings Most languages have a proper string type C uses character (byte) arrays No embedded length, end is identified by a 0 byte

Common Errors With Strings int len = strlen ( str ); char buffer [ len ]; strncpy ( buffer, str, len ); Allocates enough space for the characters in the string But not enough for the NULL terminator

Don t Forget the Terminator int len = strlen ( str ); char buffer [ len +1]; memcpy ( buffer, str, len ); buffer [ len ] = \0 ;

Unsafe String Functions strcpy ( buffer, input ); What happens if buffer is smaller than input? Memory corruption!

Slightly Less Unsafe String Functions strncpy ( buffer, input, length ); What happens if buffer is smaller than input? Silent truncation, buffer is not terminated

Safe String Functions int len = 128; char buffer [ len ]; if ( len < strlcpy ( buffer, input, len )) { // Handle case where truncation would occur } Output string is always terminated. Return value from strlcpy() is the size of input Easy to use safely Not in glibc, so unavailable on GNU/Linux

Using gets // Should be big enough char * buffer = malloc ( 1024) ; // Ooops, this function has no way of knowing how big the buffer is gets ( buffer ); It is impossible to use gets() correctly It is deprecated in C99 It is removed in C1X If someone suggests using it, ignore anything else they say about anything.

Questions?