Clarke CS240S User Manual

Browse online or download User Manual for Water pumps Clarke CS240S. CS240 Programming in C

  • Download
  • Add to my manuals
  • Print
  • Page
    / 256
  • Table of contents
  • BOOKMARKS
  • Rated. / 5. Based on customer reviews

Summary of Contents

Page 1 - CS240 Programming in C

CS240 Programming in C Gustavo Rodriguez-Rivera Purdue University

Page 2

Uses of C  Linux is written in C  Most of the libraries (low level) that need speed are written in C, Graphics (OpenGL), MP3 decoders, math librarie

Page 3 - General Information

Comma Expressions  i = (e1, e2) *comma expressions  the value of i is the last expression e2.  i=(e1, e2, e3)  the value of i is the last expressi

Page 4 - Mailing List

Arithmetic Conversion  If operands in an expression have different types the operands will have their types changed from the lower precision type to

Page 5

Arithmetic Conversion  int i; i = 'A' + 'B'; → 131 (int)  Even though 'A' and 'B' is char it is

Page 6 - Lab Policy

Assigment conversion  They happen when an expression in the right hand side has to be converted to the type in the left hand side in an assignment.

Page 7 - Grading

Cast Conversion  Done by the programmer (type) expression (int) 2.5 results into 2

Page 8 - Course Contents

typedef  typedef provides a synonym of an existing type typedef int Boolean; Boolean b; #define FALSE 0 #define TRUE 1

Page 9 - The C Language

Common Errors  “a” and ‘a’ are different  “a” is a string constant type (char *)  ‘a’ is a char constant type (int)  if (c = getchar

Page 10 - Uses of C

if Statement  if(..expression..){ ... ... }  Expression in if (exp) statement is converted to int.  If (expression) != 0 then

Page 11 - The C Principle

while statement  while(..expression..){ ... ... }  Expression in while statement is converted to an int.  while(expres

Page 12

for statement  "for" statement is typically used in situation where you know in advance the number of iterations.  Syntax: for(expr

Page 13 - C principle revisited

The C Principle “C will not get in your way to make your program run fast.”  For example an array access such as : a[i]=s;  In Java // Chec

Page 14 - Memory Usage in C and Java

for statement  However you could use the for statement where a while statement is also used. Example: expr1; while(expr2){ // b

Page 15

switch statement  switch(expr) { case const1: ... break; case const2: ... break; default: ... break; }  expr is evaluate

Page 16 - Example of a C Program

Forever Loops (Infinite Loops)  while(1){ // body runs forever }  for(;;){ // body runs forever }

Page 17 - Compiling a C program

Example: Count the number of lines, tabs and lower case characters in the input #include <stdio.h> int main(){ int countBlanks = 0; int countT

Page 18 - Example: min/max

Example: Count the number of lines, tabs and lower case characters in the input while((c = getchar()) != EOF){ switch(c){ case '

Page 19 - Example: min/max (cont.)

Example: Count the number of lines, tabs and lower case characters in the input //Within a switch statement when a "break" //is hit

Page 20

Text Files  Declared in the header #include <stdio.h>  You need a file handle to use files FILE *fileHandle;  To open a file you woul

Page 21 - Example: Implementing “grep”

Example of fopen FILE *f; f = fopen("hello.txt", "r"); if(f == NULL){ printf("Error cannot open hello.txt\n"); perro

Page 22 - Mygrep implementation

Standard Files  There are three FILE’s that are already opened when a program starts running:  stdin - standard input, It is usually the terminal un

Page 23

Basic Operations for stdin/stdout  For stdout:  int printf(...) prints formatted output to stdout  int putchar(int c) writes c to stdout  For std

Page 24 - Bits and Bytes

Out-of-bounds assignment in C int a[5]; int b[3]; a[2]=789; b[1]=45; a[6]=317; a: 0: 1: 2: 3: 4: 789 45 b: 0: 1: a and b in memory b[1] will be o

Page 25 - Memory

Basic Operations for generic FILE’s  int fgetc(fileHandle)  reads one char from fileHandle  c = getchar is equivalent to c = fgetc(stdin)  int fpu

Page 26 - “complements of two”

Basic Operations for generic FILE’s  int fprintf(fileHandle, format, ...);  prints formatted output to fileHandle  printf("Hello world %d

Page 27

Example: Read file with student grades and compute average. students.txt: Mickey 91 Donald 90 Daisy 92 students.c #include<stdio.h>

Page 28 - Representation of Strings

Example: Read file with student grades and compute average. int main(int argc, char **argv){ FILE *fd; char name[MAX_NAME + 1]; int gr

Page 29 - ASCII Table

Example: Read file with student grades and compute average. n = 0; while(fscanf(fd, "%s %d", names[n], &grades[n]

Page 30 - C String Representation

Lab3: Implementing resizable table resizable_table.h #if !defined RESIZABLE_ARRAY_H #define RESIZABLE_ARRAY_H #define INITIAL_SIZE_RESIZABLE_TABLE

Page 31 - UNICODE

Lab3: Implementing a resizable table resizable_table.cpp: #include <stdlib.h> #include <assert.h> #include <stdio.h> #include <s

Page 32 - Memory of a Program

Lab3: Implementing a resizable table // // Adds one pair name/value to the table. If the name already exists it will // Substitute its value. Otherwis

Page 33

Implementing a Double Linked List head LINKED_LIST Sentinel – It does not store any data but simplifies implementation. next previous Empty List S

Page 34 - Memory Gaps

Implementing a Double Linked List head LINKED_LIST Sentinel next previous previous next List with one element

Page 35 - Data Types and Bytes

C principle revisited “C will not get in your way to make your program run fast.” …. However, C will not protect you if you make a mistake!!!  You h

Page 36 - Sections of a Program

Adding a Node to a Double Linked List head LINKED_LIST Sentinel next previous previous next addNode(name,val) { 1:Node *e = (Node *)

Page 37

Adding a Node to a Double Linked List head LINKED_LIST Sentinel next previous previous next addNode(name,val) { 1:Node *e = (Node *)

Page 38 - Address Space

Lab3: Implementing a double-linked list linked_list.h: #if !defined LINKED_LIST_H #define LINKED_LIST_H typedef struct LINKED_LIST_ENTRY { ch

Page 39 - #include <stdlib.h>

Lab3: Implementing a double-linked list #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #inclu

Page 40

Lab3: Implementing a double-linked list // // Adds one pair name/value to the list. If the name already exists it will // Substitute its value. Otherw

Page 41 - char a[30];

Pointers A pointer is an address in memory. int a; int *p; a=5; p=&a; printf(“a= %d”,a); // prints 5 printf(“Address of a = %ld”,&a);

Page 42

Pointers A pointer is an address in memory. int a; int *p; p=&a; *p =8 a: 100 p: 200 8 100

Page 43 - char str[20];

Printing Pointers  * is “value at” operator  To print pointers we often use the “0x%lx” format since %ld may print pointers as negative numbers 

Page 44 - x.a = 'A';

Pointer Types  Pointers have types : int i; int * p; // p is an integer pointer unsigned char *q; // q is a pointer to unsigned char double * pd

Page 45

Little Endian /Big Endian  Assume the following statements: int i = 5; unsigned char * p; p = (unsigned char*) &i;  5 may be stored in two ways

Page 46 - Notes on Lab2

Memory Usage in C and Java  Java uses Garbage Collection.  The JVM will collect the objects that are unreachable by the program.  C uses explicit

Page 47 - What is GDB

Code to Determine if machine is Little Endian Int isLittleEndian() { int i = 5; unsigned char * p = (unsigned char *) &i; if (p[0] == 5) {

Page 48 - Compiling a program for gdb

Little Endian /Big Endian  Little Endian : Puts 5 at 100 (Intel, ARM, VAX)  Lowest significant byte is placed in the lowest address  Big Endian : P

Page 49 - Running a Program with gdb

Pointer Conversion  Pointer conversion is very powerful because you can read or write values of any type anywhere in memory. char buffer[64]; int *p

Page 50 - (gdb) next

Malloc and Dynamic Memory  malloc() allows us to request memory from the OS while the program is running.  Instead of pre-allocating memory (eg. M

Page 51 - Setting breakpoints

Example Using malloc int *p; p=(int *) malloc(sizeof(int)); if(p==NULL) { //Not enough memory perror(“malloc”); exit(0); } *p = 5; // malloc m

Page 52 - Regaining the Control

Memory Deallocation  When the program does not need the memory anymore, you can free it to return it to the malloc free list. free(p);  The f

Page 53 - Where is your Program

Memory Allocation Errors  Explicit Memory Allocation (calling free) uses less memory and is faster than Implicit Memory Allocation (GC)  However, Ex

Page 54 - (gdb) print var

Memory Leaks  Memory leaks are objects in memory that are no longer in use by the program but that are not freed.  This causes the application to us

Page 55 - Exiting gdb

Memory Leaks  Memory leaks is a problem for long lived applications (24/7).  Short lived applications may suffer memory leaks but that is not a prob

Page 56 - Debugging a Crashed Program

Memory Leaks Example: int * ptr; ptr = (int *) malloc(sizeof(int)); *ptr = 8; … Use ptr … ptr = (int *) malloc(sizeof(int)); // Old block pointed by p

Page 57

Memory Usage in C and Java  C programs in general use less that half the size of a Java program.  C programs can be “Fast and Lean” but you have to

Page 58

Premature Frees  A premature free is caused when an object that is still in use by the program is freed.  The freed object is added to the free list

Page 59 - Remember:

Premature Frees Example: int * p = (int *) malloc(sizeof(int)); * p = 8; free(p); // delete adds object to free list // updating header info

Page 60 - Structure of a C program

Premature Frees. Setting p to NULL after free.  One way to mitigate this problem is to set to NULL the ptr after you call free(p) int * p = (int *)

Page 61 - Compiling object files:

Double Free  Double free is caused by freeing an object that is already free.  This can cause the object to be added to the free list twice corrupti

Page 62 - Functions in Multiple Files

Double Free Example: int * p = (int *) malloc(sizeof(int)); free(p); // delete adds object to free list .. Do something else …. free(p); // deleting

Page 63 - Making functions private

Double Free. Setting p to NULL after free. int * p = (int *) malloc(sizeof(int)); free(p); // delete adds object to free list P = NULL; .. Do somethin

Page 64

Wild Frees  Wild frees happen when a program attempts to free a pointer in memory that was not returned by malloc.  Since the memory was not returne

Page 65 - Global Variables

Wild Frees  Also memory allocated with malloc() should only be deallocated with free() and memory allocated with new should only be deallocated with

Page 66

Wild Frees Example: int q; int * p = &q; free(p); // p points to an object without // header. Free will crash or // it will corrupt the f

Page 67 - Local Variables

Wild Frees Example: char * p = (char*)malloc(100); p=p+10; free(p); // p points to an object without // header. Free will crash or // i

Page 68 - Local Vars Example

Example of a C Program  Use a text editor to create the file and name it hello.c #include <stdio.h> //include file from /usr/includes/stdio.h

Page 69 - Stack Dump of fact(n)

Memory Smashing  Memory Smashing happens when less memory is allocated than the memory that will be used.  This causes overwriting the header of the

Page 70 - Static Local Vars

Memory Smashing Example: char * s = (char*)malloc(8); strcpy(s, “hello world”); // We are allocating less memory for // the string than the mem

Page 71 - Example static local var

Debugging Memory Allocation Errors  Memory allocation errors are difficult to debug since the effect may happen farther away from the cause.  Memory

Page 72 - String Functions in C

Debugging Memory Allocation Errors  There are tools that help you detect memory allocation errors.  IBM Rational Purify  Bounds Checker  Insure++

Page 73 - return dest;

Common Errors with Pointers  Use a pointer without initializing it (crashes the program SEGV)  Not allocation enough memory int *array; int n=20; ar

Page 74 - *q = *p;

Sum of a pointer and an int  A pointer is an address when you add an integer i to a pointer of type T, the integer is multiplied by the size of the t

Page 75

Pointers and Arrays int a[10]; a:100 a[0] a[1] a[2] a[3] a[9] 104: 108: 112: 136: int a[10]; int *p; p = &a[0]; // p == 100 p = p + 1; // Sinc

Page 76

Pointers And Arrays  In C, pointers are arrays and arrays are pointers. For example, int a[10];  a is an array of 10 elements of type in

Page 77 - Implementation of strlen

Pointers and Arrays int a[10]; a:100 a[0] a[1] a[2] a[3] a[9] a[1]=7 a + 1 == 104 *(a+1) == 7 104: 108: 110: 136: 7 5

Page 78 - Using malloc

Pointer Equivalence  Assume that int a[10]; int i;  We have that a[i] is the same as *(a+i) is the same as *(&a[0]+i) is the s

Page 79

Compiling a C program  To compile a program gcc -o hello hello.c “hello” is the name of the executable.  Also you may use gcc –g –o hello hello.c

Page 80

Pointer Comparison ( < >= >= == != )  You can compare two pointers.  A pointer is an unsigned long that is the address of the va

Page 81 - Lexical Structure of C

Add Elements in an Array Using Pointers int sum (int *a, int n) { nt *p; int *pend; p = &a[0]; pend = p + n; int s = 0; wh

Page 82 - Comments in C

Pointers as arrays By the same token, pointers can be treated as arrays int *p; p = a; a[0] = 5; printf("p[0] = %d\n", p[0]); Output: p[0]

Page 83 - Identifiers

Pointer subtraction  Assuming that p and q are pointers of the same type, (q – p) will give the number of objects between q and p. int

Page 84 - Keywords

Pointer Subtraction a:100 a[0] a[1] a[2] a[3] a[5] 104: 108: 112: a[4] 116: 120: p: 200 q: 204 104 120 q-p == (120-104)/4 ==4 p = &buffer[1];

Page 85 - Types of variables

Passing Arguments by Value  All arguments in a function in C are passed by a “value”, that is the value of the variable or constant is passed to the

Page 86

Passing an Argument by Reference  Passing by reference means that the variable passed in the argument can be modified inside the function.  This is

Page 87 - Constants

Swap Two Numbers Using Passing Arguments by Reference void swap(int *px, int *py) { int temp;

Page 88 - Assignment

Lab 4: RPN Calculator // Implementation of a stack #define MAXSTACK 100 double stack[MAXSTACK]; int top = 0; void push(double val) { if ( top ==

Page 89 - The Main Program

Lab 4: RPN Calculator int main( int argc, char ** argv) { // argv is the array of arguments int i; // Printing the arguments for (i=0; i <

Page 90 - Integer Constants

Example: min/max #include <stdio.h> main() { printf("Program that prints max and min of two numbers a,b\n"); int a, b

Page 91

Dangling Reference Problem  The lifetime of local variables is limited to the time the function that contains the variables is called.  You should n

Page 92 - Floating Point Constants

String Operations with Pointers  We can rewrite many of the string functions using pointers

Page 93 - Character constant

strlen using array operator int strlen(char*s) { int i=0; while(s[i]) { i++; } return; }

Page 94 - Character Constants

strlen using pointers int strlen(char *s) { int i=0; while(*s) { i++; s++; } return i; }

Page 95

strcpy using pointers char *strcpy(char*dest, char *src) { char*p =src; char*q=dest; while(*p) { *q=*p; q++; p++; } *q='\0';

Page 96 - String Constants

Strcat using pointers char *strcat(char*dest, char*src) { char *p; // make p point to end of dest p=dest; while(*p) { p++; } q=src; //copy from

Page 97 - // is never evaluated

Common Mistakes: Uninitialized pointers  Uninitialized pointers char*s; strcpy(s,"Hello\n"); // wrong s is pointing to NULL or to an /

Page 98 - Boolean and Int

Common Mistakes: Not enough space  Not enough space. s needs to include ‘\0’ at the end of the string. “Hello\0” takes 6 chars and not 5. char s[5

Page 99 - Conditional Expressions

Common Mistakes: Not enough space char s[6]; strcpy(s,"Hello"); strcat(s,"world");  s needs to have a tleast 12 characters to sto

Page 100 - Comma Expressions

strcmp(s1, s2) - String Comparison r=strcmp(s1,s2); r==0; //if s1 is equal to s2 r > 0 if s1 > s2 r < 0 if s1 < s2 strcmp("banana&q

Page 101 - Arithmetic Conversion

if (a > b) { max = a; min = b; }

Page 102

strdup –duplicate string  strdup creates a copy of the string using malloc char*strdup(char *s1) { char*s=(char *)malloc(strlen(s1)+1); strcpy(s,s1

Page 103 - Assigment conversion

Strings functions that check the string length  The functions we have seen do not check for the length of destination string.  There are equivalent

Page 104 - Cast Conversion

Passing arrays as a parameter  You can pass an array as a parameter by passing a pointer  Arrays are pointers and viceversa int sum(int a[], int si

Page 105 - b = TRUE;

Passing arrays as a parameter int sum(int *a,int size) { int sum=0; int i; for(i=0;i< size;i++) { sum+=a[i]; } return sum; } main() { in

Page 106 - Common Errors

Allocating arrays  Allocating arrays statically int array[200];  Allocating arrays using malloc int *array; int n=200; array=(int*)malloc(n*sizeo

Page 107 - if(i){

realloc(oldblock, newsize)  If you allocate memory with malloc then you can resize it. n=2*n; array=(int*)realloc(array, n*sizeof(int));  realloc(

Page 108 -  Example:

structs  A struct is a compound type: struct z { int a; double x; char *s; }r;  If you want to refer to any of the members: r.x = 23.5; r.s = &

Page 109 - Example:

structs member variables  You can name a struct so you can refer to it in multiple places struct STUDENT { char*name; double grade; };  Then def

Page 110

Pointers to struct  If the struct variable is a pointer struct STUDENT *p; p=&peter;  Then we can refer to fields of peter as follows: (*p).nam

Page 111 -  switch(expr) {

typedef struct  Using typedef and structs we can also write: typedef struct { char*name; double grade; }STUDENT; STUDENT peter, mary;  Or we can

Page 112 - // body runs forever

To report an emergency, call 911. To obtain updates regarding an ongoing emergency, sign up for Purdue Alert text messages, view www.purdue.edu/e

Page 113 - #include <stdio.h>

cs240@data ~/2014Fall/lab1/lab1-src $ gcc -o minmax minmax.c cs240@data ~/2014Fall/lab1/lab1-src $ ./minmax Program that prints max and min of two n

Page 114

Single Linked List - Header File single_linked_list.h: typedef struct SLLENTRY { char * name; char * address; struct SLLENTRY * next;//pointer to

Page 115

Single Linked List - Header File //Interface // Initialize a new list Void sllist_init(SLLIST * ); // Print List void sllist_print(SLLIST * sllist);

Page 116 - Text Files

Single Linked List - Test Main sllist_test.c: #include "single_linked_list.h“ int main() { SLLIST sl; int result; sllist_init(&sl); // w

Page 117 - Example of fopen

Single Linked List - Test Main char* addr = sllist_lookup(&sl,"Clark Kent"); if( addr == NULL) { printf("cannot find Clark's

Page 118 - Standard Files

Single Linked List - Initialize List single_linked_list.c: #include"single_linked_list.h“ // Initialize Linked list void sllist_init(SLLIST * s

Page 119 - For stdin

Single Linked List - Print List void sllist_print(SLLIST * sl) { // Traverse the list and print each element SLLENTRY *p; p = sl->head; //we initi

Page 120 - &i);

Single Linked List - Lookup char sllist_lookup(SLLIST*sl, char* name) { SLLENTRY *p; p = sl->head; while(p != NULL) { if(strcmp(name,

Page 121

Single Linked List – Add 1 int sllist_add(SLLIST* sl, char* name, char*address) { SLLENTRY *p; // we first have to check if the name already exist

Page 122

Single Linked List – Add 2 // we have exited out of the while loop and // name does not exist. We need to create a new entry p = (SLLENTRY*)ma

Page 123

Single Linked List – Remove 1 int sllist_remove(SLLIST *sl, char*name); { SLLENTRY* p = sl->head; SLLENTRY* prev = NULL; //prev is a poin

Page 124 - n = 0;

Example: Implementing “grep”  grep is a UNIX command that is used to print the lines of a file that match a given pattern. grep pattern file  Exa

Page 125 - char * name;

Single Linked List – Remove 2 if(p == NULL) { // element does not exist return 0; } // Now the entry pointed by p has the name we

Page 126

Single Linked List – Remove 3 if (prev == NULL) { sl->head = p->next; } else { prev->next = p->next ; } // Now we have

Page 127 - //

Double Linked Lists  Each node also has a previous that point sto the previous element of the list.  They have faster access to insert or remove two

Page 128 - Empty List

Double Linked Lists  By having a sentinel we will never need to modify the head except at the time of crating it.  See DLList.h and DLList.c in lab3

Page 129 - List with one element

Pointer to Functions  In the same way that you have pointers to data, you can have pointers to functions.  Pointers to functions point to functions

Page 130 - Sentinel

Use of pointer to functions: Sorting Any Array  Polymorphism: You can write in C functions that can be used for variables of multiple types. Ex:

Page 131

Use of pointer to functions: Sorting Any Array void sortAnyArray(void * array, int n, int elementsize, compare_func comp) { // Temporal mem

Page 132 - } LINKED_LIST;

Use of pointer to functions: Sorting Any Array //sort in ascending order //swap if e1>e2 //element at j is larger than in j+1 if((*comp)(e1,e2)>

Page 133 - #include <string.h>

Use of pointer to functions: Sorting Any Array //Using sorting function int main(){ // Sorting array of type int int a[] = {7,8,1,4,3,2}

Page 134 - return NULL;

Use of pointer to functions: Sorting Any Array // String comparison int compstr(void *e1, void *e2) { char **p1 = (char**)e1; char **p2

Page 135 - Pointers

Mygrep implementation /* * mygrep: Print the lines of a file that match a string * * mygrep pattern file */ #include <stdio.h> #define MAXLI

Page 136

Example of Pointers to Functions: Iterating over a List  We can use pointers to functions to iterate over a data structure and call a function pas

Page 137 - Printing Pointers

Example of Pointers to Functions: Iterating over a List single_linked_list.c //call llistfunc() in every element of linked list void sllist_mapper(SL

Page 138 - Pointer Types

Example of Pointers to Functions: Iterating over a List main.c #include “linked_list.h” void printEntry(char *name, char* value) { printf(“na

Page 139 - Little Endian /Big Endian

Example of Pointers to Functions: Iterating over a List main() { //read a linkedlist from disk SLLIST list; list = llist_init(&am

Page 140 - Int isLittleEndian()

Building a Program Programmer C Preprocessor Compiler(cc) Optimizer Assembler (as) (static) Linker (ld) Editor hello.c hello.i hello.s hello.o Execu

Page 141

Building a Program The programmer writes a program hello.c The preprocessor expands #define, #include, #ifdef etc preprocessor statements and generate

Page 142 - Pointer Conversion

Building a program The linker puts together all object files as well as the object files in static libraries. The linker also takes the definitions in

Page 143 - Malloc and Dynamic Memory

Original file hello.c #include <stdio.h> main() { printf("Hello\n"); }

Page 144 - Example Using malloc

After preprocessor gcc -E hello.c > hello.i (-E stops compiler after running preprocessor) hello.i: /* Expanded /usr/include/stdio.h */ ty

Page 145 - Memory Deallocation

After assembler gcc -S hello.c (-S stops compiler after assembling) hello.s: .align 8 .LLC0: .asciz "Hello\n" .section &qu

Page 146 - Memory Allocation Errors

Mygrep implementation (cont.) void mygrep(char * fileName, char * pattern) { FILE * fd = fopen(fileName,"r"); if (fd == NULL) { prin

Page 147 - Memory Leaks

After compiling “gcc -c hello.c” generates hello.o hello.o has undefined symbols, like the printf function call that we don’t know where it is placed

Page 148

After linking “gcc –o hello hello.c” generates the hello executable Printf does not have a value yet until the program is loaded csh> nm hello [Ind

Page 149

Loading a Program The loader is a program that is used to run an executable file in a process. Before the program starts running, the loader allocates

Page 150 - Premature Frees

Loading a Program It also writes (resolves) any values in the executable to point to the functions/variables in the shared libraries.(E.g. calls to pr

Page 151

Loading a Program Loader (runtime linker) (/usr/lib/ld.so.1) Executable File Executable in memory Shared libraries (.so, .dll)

Page 152

Static and Shared Libraries Shared libraries are shared across different processes. There is only one instance of each shared library for the entire

Page 153 - Double Free

The C Preprocessor: Macro Definitions #define  Macro Definitions are used to define constants or functions that need to be in-lined #define PI

Page 154

Be careful with macros //returns true if c is lowercase… #define islower(c) (c>=’a’&&c<=’z’) if(islower(x+1)){

Page 155 - .. Do something else …

The C Preprocessor: Macro Definitions #define  Another example of a macro // get one character from a file #define getchar() fgetc(stdin)  A ma

Page 156 - Wild Frees

The C Preprocessor: File Inclusion #include  Examples of file inclusion #include “FILENAME” //It will search for the file in the current dire

Page 157

Bits and Bytes  Bits are grouped in bytes, where each byte is made of 8 bits.  In modern computers a byte is the smallest unit that can be addresse

Page 158

The C Preprocessor: Conditional Compilation #if Examples of conditional compilation #if constantexpr1 //evaluated by preprocessor, before compilati

Page 159

The C Preprocessor: Conditional Compilation #if  Conditional Compilation is useful if we have various environment, say Solaris, Linux, Windows……  E

Page 160 - Memory Smashing

The C Preprocessor: Conditional Compilation #if  You may use conditional compilatiion to comment multiple lines of code that have comments already 

Page 161

The C Preprocessor: Conditional Compilation #ifdef and #ifndef  #ifndef is often used in include files to prevent include files from being included m

Page 162

Some Predefined Macros Some predefined macros: _ _LINE_ _ Expands to the line number _ _FILE_ _ Expands to the file name _ _TIME

Page 163 - Dr. Memory

 EXAMPLE #define MyAssert(x) \ if(!(x)){ \ printf(“Assertion failed!%s:%d\n”, \ _ _FILE_ _, _ _LINE_ _); \ } main{

Page 164 - Common Errors with Pointers

Assertions  Assertions like the one above are useful for “defensive” programming.  It is better to have an assertion failure than a segmentation fau

Page 165 - Sum of a pointer and an int

Bit Operations: Left and Right Shift << >>  x >> i  Shifts bits of a number x to the right i positions  x << i  Sh

Page 166 - Pointers and Arrays

Left and Right Shift << >> with sign extension.  When using i >> n (shift right) the behavior will change if i is a signed int or

Page 167 - Pointers And Arrays

Bitwise Operations: OR |  The “|” operator executes “OR” bit operation. unsigned x = 0x05; // 00000101 unsigned y = (x | 0x2); // 000001

Page 168

Representation of Numbers in Memory  Integers are represented in groups of  1 byte (char)  2 bytes (short int or short),  4 bytes (int) , 

Page 169 - Pointer Equivalence

Bitwise Operations: AND &  The “&” operator executes “AND” bit operation. unsigned x = 0x05; // 00000101 unsigned y =(x | 0x3);// 00000101

Page 170 - Pointer Comparison

Bitwise Operations: XOR ^  The “^” operator executes “XOR” bit operation.  XOR : 0^0==0, 0 ^1 == 1, 1^0==1, 1^1==0 unsigned x = 0x05; // 00000101

Page 171

Bitwise Operations: NOT ~  The “~” negates bits. unsigned x = 0x05; // 0000000 0000000 0000000 00000101 unsigned y = ~x; // ~00000101 = 1111111

Page 172 - Pointers as arrays

Using Bitwise Operations: Test if bit i is set: int i = 4; unsigned x = 23; // x = 00010111 // Test if bit i is set in x // Create mask with

Page 173 - Pointer subtraction

Using Bitwise Operations: Set bit i : int i = 3; unsigned x = 23; // x = 00010111 // Set bit i in x // Create mask with bit i set. unsigned m

Page 174 - Pointer Subtraction

Using Bitwise Operations: Clear bit i : int i = 2; unsigned x = 23; // x = 00010111 // Set bit i in x // Create mask with bit i set. unsigned

Page 175 - Passing Arguments by Value

Unions  A union is like a struct but all the elements use the same memory.  That means that modifying one element will overwrite the other elements.

Page 176

Representation of Negative Numbers in Memory  Negative numbers typically use a representation called “complements of two”,  A negative number is ob

Page 177 - Arguments by Reference

Complements of Two and Addition  If we have the binary representation of 8987794 added to same number in complements of two representing -8987794 we

Page 178 - Lab 4: RPN Calculator

Representation of Strings  Basic strings in C language are represented in memory as a sequence of bytes delimited by a 0 value.  Each byte represen

Page 179

ASCII Table 32: 48:0 64:@ 80:P 96:` 112:p 33:! 49:1 65:A 81:Q 97:a 113:q 34:" 50:2 66:B 82:R 98:b 114:r 35:# 51:3 67:C 83:S 99:c 115:s 36:

Page 180 - Dangling Reference Problem

General Information Web Page: http://www.cs.purdue.edu/homes/cs240 Office: LWSN1210 E-mail: [email protected] Textbook:  “The C programming Language

Page 181

C String Representation  For example, the string “Hello world is represented by the equivalent ASCII characters delimited by a NULL character.

Page 182 - return;

UNICODE  To be able to represent characters in other languages, the Unicode standard was created.  Unicode extends the ASCII standard and it uses t

Page 183

Memory of a Program  From the point of view of a program, the memory in the computer is an array of bytes  This array goes from address 0 to address

Page 184 - char*q=dest;

Computer Memory as an Array of Bytes

Page 185 - Strcat using pointers

Memory Gaps  Every program that runs in memory will see the memory this way.  In C/C++ or assembly language it is possible to access the location

Page 186 -  Solution:

Data Types and Bytes  Types such as integers, floats, doubles, or strings are represented as one or more of these bytes in memory.  Everything stor

Page 187 - char s[5];

Sections of a Program  The memory of the computer is used to store both the program code, and the data that the program manipulates.  An executabl

Page 188 - "Hello world \0"

Sections of a Program

Page 189

Address Space  Each program has its own view of the memory that is independent of each other.  This view is called the “Address Space” of the progra

Page 190

Printing Program Memory Addresses #include <stdlib.h> #include <stdio.h> int a = 5; // Stored in data section int b[20]; // Stored in b

Page 191

Mailing List All announcements will be sent via email and posted in Piazza. Mailing List will be created automatically

Page 192 - same as

Printing Program Memory Addresses cs240@data ~/2014Fall/LectureNotes/test $ ./test1 sizeof(int)=4 sizeof(long)=8 sizeof(int*)=8 (TEXT) main=0x4005bc

Page 193 - return sum;

Simple Memory Dump of a Program  In Lab2 you will write a memory dump function that will print the memory dump of a program: Hint: Use char *

Page 194 - Allocating arrays

Simple Memory Dump of a Program cs240@data ~/2014Fall/lab2 $ gcc -o hintdump hintdump.c cs240@data ~/2014Fall/lab2 $ ./hintdump 0x00007FFF150B1A9C:

Page 195 - Frees the old block

Examining the memory of the program: cs240@data ~/2014Fall/lab2/lab2-src-sol $ cat mem.c #include <stdio.h> #include <string.h> #include &

Page 196 - A struct is a compound type:

Examining the memory of the program: x.a = 'A'; x.i = 9; x.b = '0'; x.p = &x.i; strcpy(str, "Hello world\n"

Page 197

Examining the memory of the program cs240@data ~/2014Fall/lab2/lab2-src-sol $ ./mem &str=0x7FFFCFB29B50 &a=0x7FFFCFB29B4C &b=0x7FFFCFB29B4

Page 198 - Pointers to struct

Notes on Lab2 Important for lab2: Copy the new mem.c from https://www.cs.purdue.edu/homes/cs240/lab2/lab2-src/mem.c The new one mem.c prints the a

Page 199 - }STUDENT;

What is GDB GDB is a debugger that helps you debug your program. The time you spend now learning gdb will save you days of debugging time. A debugger

Page 200 - char * address;

Compiling a program for gdb You need to compile with the “-g” option to be able to debug a program with gdb. The “-g” option adds debugging informatio

Page 201

Running a Program with gdb To run a program with gdb type gdb progname (gdb) Then set a breakpoint in the main function. (gdb) break main A breakpoint

Page 202

Labs Lab 1 is already posted. It is due Monday. Post your questions in Piazza You may attend the second hour of any lab to ask for help. Also you ma

Page 203

Stepping Through your Program Your program will start running and when it reaches “main()” it will stop. gdb> Now you have the following commands

Page 204

Setting breakpoints You can set breakpoints in a program in multiple ways: (gdb) break function Set a breakpoint in a function E.g. (gdb) break main

Page 205 - p = p->next;

Regaining the Control When you type (gdb) run the program will start running and it will stop at a break point. If the program is running without st

Page 206 - Single Linked List - Lookup

Where is your Program The command (gdb)where Will print the current function being executed and the chain of functions that are calling that fuction.

Page 207 - Single Linked List – Add 1

Printing the Value of a Variable The command (gdb) print var Prints the value of a variable. E.g. (gdb) print i $1 = 5 (gdb) print s1 $1 = 0x

Page 208 - Single Linked List – Add 2

Exiting gdb The command “quit” exits gdb. (gdb) quit The program is running. Exit anyway? (y or n) y

Page 209

Debugging a Crashed Program This is also called “postmortem debugging” It has nothing to do with CSI  When a program crashes, it writes a core file.

Page 210 - if(p == NULL)

Debugging a Crashed Program  Sometimes the sysadmins disable the generation of core files to reduce the disk space waste. This happens in the CS mach

Page 211 - // to allocate memory to it

Debugging a Crashed Program To run gdb in a crashed program type gdb program core E.g. bash-4.1$ gdb hello core GNU gdb 6.6 Program terminated with si

Page 212 - Double Linked Lists

Now Try gdb in Your Own Program Make sure that your program is compiled with the –g option. Remember:  One hour you spend learning gdb will save you

Page 213

Lab Policy  Do your project on your own.  It is OK to discuss about your labs but at the time of coding do it on your own.  We will check projects

Page 214 - Pointer to Functions

Structure of a C program  A C program is a sequence of definitions of functions, and global variables, type definitions and function prototypes: glob

Page 215 - int * p1 = (int *)e1;

Compiling from multiple files  Compiling object files:  You may compile each file separately and then link them: gcc –c sum.c - Generates sum.

Page 216 - compare_func comp)

Functions in Multiple Files  A function defined in one file can be used in another file.  The second file needs to have an extern definition: sum

Page 217 -

Making functions private  You can make a function private to a file by adding the static keyword before the function declaration. static void mylocal

Page 218

Scope and Lifetime of a variable  Scope = The place in the program where a variable can be used.  Lifetime = The time in the execution when a variab

Page 219

Global Variables  Global Variables are defined outside a function.  The Scope of a Global Variable is from where it is defined to the end of the fil

Page 220 - Iterating over a List

Global Variables in Multiple Files sum.c: extern int total; // extern declaration void sum( int a, int b) { total = a + b; } main.c: #include <

Page 221

Local Variables  Local variables are defined inside functions  The Scope of a Local Variable is from where it is defined to the end of the function.

Page 222

Local Vars Example #include <stdio.h> int fact(int n) { int val; printf("fact(%d)\n", n); if (n == 1) { mymemdump(stdout,

Page 223

Stack Dump of fact(n) 0x00007FFFF837243C: 01 00 00 00 28 26 37 F8 FF 7F 00 00 02 07 40 00 ...(&7...@. 0x00007FFFF837244C: 01 00 00 00 80 24 37

Page 224 - Building a Program

Grading Grade allocation  Midterm: 25%  Final: 25%  Projects: 50% Exams will include programming questions.

Page 225

Static Local Vars  If you add the keyword static before a local variable it will make the value of the variable be preserved across function invocati

Page 226 - Building a program

Example static local var int sum(int a) { static int i; i += a; printf(“i=%d\n”); } main() { sum(4); sum(5); sum(6); } Output: 4 9 1

Page 227 - Original file hello.c

String Functions in C  C Provides string functions such as:  strcpy(char *dest, char *src)  Copy string src to dest.  int strlen(char * s)  Re

Page 228 - After preprocessor

Implementation of strcpy using array operator. char * strcpy(char * dest, char * src) { int i = 0; while (src[i] != ‘\0’) { dest[i] =

Page 229 - After assembler

Implementation of strcpy using pointers Implementation of strcpy using pointer operations. char * strcpy(char * dest, char * src) { char * p = sr

Page 230 - After compiling

Implementation of strcpy using pointers p:100 q: 200 4000 Memory 5000 4000: H i 0 5000: *q = *p q++; p++; p:100 q: 200 4001 Memory 5001 4000: H i

Page 231 - After linking

Implementation of strcpy using pointers p:100 q: 200 4002 Memory 5002 4000: H i 0 5000: *q = 0 p:100 q: 200 4003 Memory 5003 4000: H i 0 5000:

Page 232 - Loading a Program

Implementation of strlen char * strlen(char * src) { int i = 0; while (src[i] != ‘\0’) { i++; } return i; }

Page 233

Using malloc  Malloc is used to allocate memory from the system.  It is similar to “new” in Java but there is no constructor associated to it.  Exa

Page 234

Allocating an array using malloc  You may allocate memory for an array in the same way:  Example: int * array; int N = 10; array = (int *) malloc(N*

Page 235 - Static and Shared Libraries

Course Contents  C development cycle:  C Programming Structure  Control Flow  While/for/do, etc  Functions  Arrays & Strings  Pointer  Dy

Page 236 - #define

Allocating an array using malloc  When memory is no longer in use call free(p);  If memory is not freed, the memory used by the program will increas

Page 237 - Be careful with macros

Lexical Structure of C A program is a sequence of characters in a text file. hello.c |*...*| int main() { printf(“He

Page 238

Comments in C  Comments  /*...*/ same as Java  //... available in most compilers but it is not in standard.

Page 239 -  Example of an include file

Identifiers  Sequence of letters, underscore and digits that do not start with a digit  Only first 37 chars are significant  Mix lower and upper ca

Page 240 - Compilation #if

Keywords  Special keywords. while,break, for, case, break,continue, int...

Page 241

Types of variables int a; // Signed Integer 4 bytes long b; // Signed integer 8 bytes short s; // Signed integer 2 bytes char c; // S

Page 242

Types of variables float ff; // Floating Point number 4 bytes double dd; // Floating Point number 8 bytes long double ddd; // Floating Point 1

Page 243 - #ifndef STDIO_H

Constants  Same as Java. const double PI = 3.14192654;  constants cannot be changed  Also it is common in C to use the C pre-processor to define v

Page 244 - Some Predefined Macros

Assignment  The element in the left side has to be an “l-value”. An “l-value” can be interpreted as an address.  A variable is an l-value but a con

Page 245 - EXAMPLE

The Main Program  Execution starts in main int main(int argc, char**argv){ } or int main(){ }  argc-store # of args.  a

Page 246 - Assertions

The C Language  C was created by Dennis Ritchie in 1972 in Bell Labs  C was used to implement UNIX  Operating Systems used to be implemented 100% i

Page 247 - Bit Operations:

Integer Constants  Integer Constants 1 2 3 4 → decimal 031 → octal constant 3*8+1 = 25 Starts with 0 0x4A3 → hexadecimal constant 4*16^2+10*16+3= or

Page 248

Integer Constants  You can add suffix to force type  123456789L → long  55u → unsigned int  234Lu → unsigned long

Page 249 - Bitwise Operations: OR

Floating Point Constants  3.14 → type is always double  To force the type float, add “f” suffix.  3.14f → float constant

Page 250

Character constant  'q' enclosed with a single quote.  Also you can use escape sequences with '\octal number' e.g. '\020’

Page 251 - Bitwise Operations: XOR ^

Character Constants  Also there are some common escape sequences '\n' → new line  '\r' → return  '\t'

Page 252 - Bitwise Operations: NOT ~

Character Constants  Character constants have type int. int i; i = 'A'; //assign ascii 65 to I Or i = 65; printf(“A = %d\n”, &apo

Page 253 - Using Bitwise Operations:

String Constants  “My String” is a string constant of type (char *)  There are no operations with string in Java like “Hello”+”world”.  However, t

Page 254

Short-Circuit && (and) and || or expression  e1 && e2 is the short circuit “and” expression  If e1 is false, e2 is not evaluated.

Page 255

Boolean and Int  There is no Boolean type  A 0 is False and anything different than 0 is True.  if(5){ //always executed } if(0

Page 256

Conditional Expressions  e = (e1 ? e2 : e3) *conditional expression Equivalent to if(e1){ e = e2; }

Comments to this Manuals

No comments