CS240 Programming in C Gustavo Rodriguez-Rivera Purdue University
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
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
Arithmetic Conversion If operands in an expression have different types the operands will have their types changed from the lower precision type to
Arithmetic Conversion int i; i = 'A' + 'B'; → 131 (int) Even though 'A' and 'B' is char it is
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.
Cast Conversion Done by the programmer (type) expression (int) 2.5 results into 2
typedef typedef provides a synonym of an existing type typedef int Boolean; Boolean b; #define FALSE 0 #define TRUE 1
Common Errors “a” and ‘a’ are different “a” is a string constant type (char *) ‘a’ is a char constant type (int) if (c = getchar
if Statement if(..expression..){ ... ... } Expression in if (exp) statement is converted to int. If (expression) != 0 then
while statement while(..expression..){ ... ... } Expression in while statement is converted to an int. while(expres
for statement "for" statement is typically used in situation where you know in advance the number of iterations. Syntax: for(expr
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
for statement However you could use the for statement where a while statement is also used. Example: expr1; while(expr2){ // b
switch statement switch(expr) { case const1: ... break; case const2: ... break; default: ... break; } expr is evaluate
Forever Loops (Infinite Loops) while(1){ // body runs forever } for(;;){ // body runs forever }
Example: Count the number of lines, tabs and lower case characters in the input #include <stdio.h> int main(){ int countBlanks = 0; int countT
Example: Count the number of lines, tabs and lower case characters in the input while((c = getchar()) != EOF){ switch(c){ case '
Example: Count the number of lines, tabs and lower case characters in the input //Within a switch statement when a "break" //is hit
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
Example of fopen FILE *f; f = fopen("hello.txt", "r"); if(f == NULL){ printf("Error cannot open hello.txt\n"); perro
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
Basic Operations for stdin/stdout For stdout: int printf(...) prints formatted output to stdout int putchar(int c) writes c to stdout For std
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
Basic Operations for generic FILE’s int fgetc(fileHandle) reads one char from fileHandle c = getchar is equivalent to c = fgetc(stdin) int fpu
Basic Operations for generic FILE’s int fprintf(fileHandle, format, ...); prints formatted output to fileHandle printf("Hello world %d
Example: Read file with student grades and compute average. students.txt: Mickey 91 Donald 90 Daisy 92 students.c #include<stdio.h>
Example: Read file with student grades and compute average. int main(int argc, char **argv){ FILE *fd; char name[MAX_NAME + 1]; int gr
Example: Read file with student grades and compute average. n = 0; while(fscanf(fd, "%s %d", names[n], &grades[n]
Lab3: Implementing resizable table resizable_table.h #if !defined RESIZABLE_ARRAY_H #define RESIZABLE_ARRAY_H #define INITIAL_SIZE_RESIZABLE_TABLE
Lab3: Implementing a resizable table resizable_table.cpp: #include <stdlib.h> #include <assert.h> #include <stdio.h> #include <s
Lab3: Implementing a resizable table // // Adds one pair name/value to the table. If the name already exists it will // Substitute its value. Otherwis
Implementing a Double Linked List head LINKED_LIST Sentinel – It does not store any data but simplifies implementation. next previous Empty List S
Implementing a Double Linked List head LINKED_LIST Sentinel next previous previous next List with one element
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
Adding a Node to a Double Linked List head LINKED_LIST Sentinel next previous previous next addNode(name,val) { 1:Node *e = (Node *)
Adding a Node to a Double Linked List head LINKED_LIST Sentinel next previous previous next addNode(name,val) { 1:Node *e = (Node *)
Lab3: Implementing a double-linked list linked_list.h: #if !defined LINKED_LIST_H #define LINKED_LIST_H typedef struct LINKED_LIST_ENTRY { ch
Lab3: Implementing a double-linked list #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #inclu
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
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);
Pointers A pointer is an address in memory. int a; int *p; p=&a; *p =8 a: 100 p: 200 8 100
Printing Pointers * is “value at” operator To print pointers we often use the “0x%lx” format since %ld may print pointers as negative numbers
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
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
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
Code to Determine if machine is Little Endian Int isLittleEndian() { int i = 5; unsigned char * p = (unsigned char *) &i; if (p[0] == 5) {
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
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
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
Example Using malloc int *p; p=(int *) malloc(sizeof(int)); if(p==NULL) { //Not enough memory perror(“malloc”); exit(0); } *p = 5; // malloc m
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
Memory Allocation Errors Explicit Memory Allocation (calling free) uses less memory and is faster than Implicit Memory Allocation (GC) However, Ex
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
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
Memory Leaks Example: int * ptr; ptr = (int *) malloc(sizeof(int)); *ptr = 8; … Use ptr … ptr = (int *) malloc(sizeof(int)); // Old block pointed by p
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
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
Premature Frees Example: int * p = (int *) malloc(sizeof(int)); * p = 8; free(p); // delete adds object to free list // updating header info
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 *)
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
Double Free Example: int * p = (int *) malloc(sizeof(int)); free(p); // delete adds object to free list .. Do something else …. free(p); // deleting
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
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
Wild Frees Also memory allocated with malloc() should only be deallocated with free() and memory allocated with new should only be deallocated with
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
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
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
Memory Smashing Memory Smashing happens when less memory is allocated than the memory that will be used. This causes overwriting the header of the
Memory Smashing Example: char * s = (char*)malloc(8); strcpy(s, “hello world”); // We are allocating less memory for // the string than the mem
Debugging Memory Allocation Errors Memory allocation errors are difficult to debug since the effect may happen farther away from the cause. Memory
Debugging Memory Allocation Errors There are tools that help you detect memory allocation errors. IBM Rational Purify Bounds Checker Insure++
Common Errors with Pointers Use a pointer without initializing it (crashes the program SEGV) Not allocation enough memory int *array; int n=20; ar
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
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
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
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
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
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
Pointer Comparison ( < >= >= == != ) You can compare two pointers. A pointer is an unsigned long that is the address of the va
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
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]
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
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];
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
Passing an Argument by Reference Passing by reference means that the variable passed in the argument can be modified inside the function. This is
Swap Two Numbers Using Passing Arguments by Reference void swap(int *px, int *py) { int temp;
Lab 4: RPN Calculator // Implementation of a stack #define MAXSTACK 100 double stack[MAXSTACK]; int top = 0; void push(double val) { if ( top ==
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 <
Example: min/max #include <stdio.h> main() { printf("Program that prints max and min of two numbers a,b\n"); int a, b
Dangling Reference Problem The lifetime of local variables is limited to the time the function that contains the variables is called. You should n
String Operations with Pointers We can rewrite many of the string functions using pointers
strlen using array operator int strlen(char*s) { int i=0; while(s[i]) { i++; } return; }
strlen using pointers int strlen(char *s) { int i=0; while(*s) { i++; s++; } return i; }
strcpy using pointers char *strcpy(char*dest, char *src) { char*p =src; char*q=dest; while(*p) { *q=*p; q++; p++; } *q='\0';
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
Common Mistakes: Uninitialized pointers Uninitialized pointers char*s; strcpy(s,"Hello\n"); // wrong s is pointing to NULL or to an /
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
Common Mistakes: Not enough space char s[6]; strcpy(s,"Hello"); strcat(s,"world"); s needs to have a tleast 12 characters to sto
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
if (a > b) { max = a; min = b; }
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
Strings functions that check the string length The functions we have seen do not check for the length of destination string. There are equivalent
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
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
Allocating arrays Allocating arrays statically int array[200]; Allocating arrays using malloc int *array; int n=200; array=(int*)malloc(n*sizeo
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(
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 = &
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
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
typedef struct Using typedef and structs we can also write: typedef struct { char*name; double grade; }STUDENT; STUDENT peter, mary; Or we can
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
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
Single Linked List - Header File single_linked_list.h: typedef struct SLLENTRY { char * name; char * address; struct SLLENTRY * next;//pointer to
Single Linked List - Header File //Interface // Initialize a new list Void sllist_init(SLLIST * ); // Print List void sllist_print(SLLIST * sllist);
Single Linked List - Test Main sllist_test.c: #include "single_linked_list.h“ int main() { SLLIST sl; int result; sllist_init(&sl); // w
Single Linked List - Test Main char* addr = sllist_lookup(&sl,"Clark Kent"); if( addr == NULL) { printf("cannot find Clark's
Single Linked List - Initialize List single_linked_list.c: #include"single_linked_list.h“ // Initialize Linked list void sllist_init(SLLIST * s
Single Linked List - Print List void sllist_print(SLLIST * sl) { // Traverse the list and print each element SLLENTRY *p; p = sl->head; //we initi
Single Linked List - Lookup char sllist_lookup(SLLIST*sl, char* name) { SLLENTRY *p; p = sl->head; while(p != NULL) { if(strcmp(name,
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
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
Single Linked List – Remove 1 int sllist_remove(SLLIST *sl, char*name); { SLLENTRY* p = sl->head; SLLENTRY* prev = NULL; //prev is a poin
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
Single Linked List – Remove 2 if(p == NULL) { // element does not exist return 0; } // Now the entry pointed by p has the name we
Single Linked List – Remove 3 if (prev == NULL) { sl->head = p->next; } else { prev->next = p->next ; } // Now we have
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
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
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
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:
Use of pointer to functions: Sorting Any Array void sortAnyArray(void * array, int n, int elementsize, compare_func comp) { // Temporal mem
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)>
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}
Use of pointer to functions: Sorting Any Array // String comparison int compstr(void *e1, void *e2) { char **p1 = (char**)e1; char **p2
Mygrep implementation /* * mygrep: Print the lines of a file that match a string * * mygrep pattern file */ #include <stdio.h> #define MAXLI
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
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
Example of Pointers to Functions: Iterating over a List main.c #include “linked_list.h” void printEntry(char *name, char* value) { printf(“na
Example of Pointers to Functions: Iterating over a List main() { //read a linkedlist from disk SLLIST list; list = llist_init(&am
Building a Program Programmer C Preprocessor Compiler(cc) Optimizer Assembler (as) (static) Linker (ld) Editor hello.c hello.i hello.s hello.o Execu
Building a Program The programmer writes a program hello.c The preprocessor expands #define, #include, #ifdef etc preprocessor statements and generate
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
Original file hello.c #include <stdio.h> main() { printf("Hello\n"); }
After preprocessor gcc -E hello.c > hello.i (-E stops compiler after running preprocessor) hello.i: /* Expanded /usr/include/stdio.h */ ty
After assembler gcc -S hello.c (-S stops compiler after assembling) hello.s: .align 8 .LLC0: .asciz "Hello\n" .section &qu
Mygrep implementation (cont.) void mygrep(char * fileName, char * pattern) { FILE * fd = fopen(fileName,"r"); if (fd == NULL) { prin
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
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
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
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
Loading a Program Loader (runtime linker) (/usr/lib/ld.so.1) Executable File Executable in memory Shared libraries (.so, .dll)
Static and Shared Libraries Shared libraries are shared across different processes. There is only one instance of each shared library for the entire
The C Preprocessor: Macro Definitions #define Macro Definitions are used to define constants or functions that need to be in-lined #define PI
Be careful with macros //returns true if c is lowercase… #define islower(c) (c>=’a’&&c<=’z’) if(islower(x+1)){
The C Preprocessor: Macro Definitions #define Another example of a macro // get one character from a file #define getchar() fgetc(stdin) A ma
The C Preprocessor: File Inclusion #include Examples of file inclusion #include “FILENAME” //It will search for the file in the current dire
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
The C Preprocessor: Conditional Compilation #if Examples of conditional compilation #if constantexpr1 //evaluated by preprocessor, before compilati
The C Preprocessor: Conditional Compilation #if Conditional Compilation is useful if we have various environment, say Solaris, Linux, Windows…… E
The C Preprocessor: Conditional Compilation #if You may use conditional compilatiion to comment multiple lines of code that have comments already
The C Preprocessor: Conditional Compilation #ifdef and #ifndef #ifndef is often used in include files to prevent include files from being included m
Some Predefined Macros Some predefined macros: _ _LINE_ _ Expands to the line number _ _FILE_ _ Expands to the file name _ _TIME
EXAMPLE #define MyAssert(x) \ if(!(x)){ \ printf(“Assertion failed!%s:%d\n”, \ _ _FILE_ _, _ _LINE_ _); \ } main{
Assertions Assertions like the one above are useful for “defensive” programming. It is better to have an assertion failure than a segmentation fau
Bit Operations: Left and Right Shift << >> x >> i Shifts bits of a number x to the right i positions x << i Sh
Left and Right Shift << >> with sign extension. When using i >> n (shift right) the behavior will change if i is a signed int or
Bitwise Operations: OR | The “|” operator executes “OR” bit operation. unsigned x = 0x05; // 00000101 unsigned y = (x | 0x2); // 000001
Representation of Numbers in Memory Integers are represented in groups of 1 byte (char) 2 bytes (short int or short), 4 bytes (int) ,
Bitwise Operations: AND & The “&” operator executes “AND” bit operation. unsigned x = 0x05; // 00000101 unsigned y =(x | 0x3);// 00000101
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
Bitwise Operations: NOT ~ The “~” negates bits. unsigned x = 0x05; // 0000000 0000000 0000000 00000101 unsigned y = ~x; // ~00000101 = 1111111
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
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
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
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.
Representation of Negative Numbers in Memory Negative numbers typically use a representation called “complements of two”, A negative number is ob
Complements of Two and Addition If we have the binary representation of 8987794 added to same number in complements of two representing -8987794 we
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
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:
General Information Web Page: http://www.cs.purdue.edu/homes/cs240 Office: LWSN1210 E-mail: [email protected] Textbook: “The C programming Language
C String Representation For example, the string “Hello world is represented by the equivalent ASCII characters delimited by a NULL character.
UNICODE To be able to represent characters in other languages, the Unicode standard was created. Unicode extends the ASCII standard and it uses t
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
Computer Memory as an Array of Bytes
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
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
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
Sections of a Program
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
Printing Program Memory Addresses #include <stdlib.h> #include <stdio.h> int a = 5; // Stored in data section int b[20]; // Stored in b
Mailing List All announcements will be sent via email and posted in Piazza. Mailing List will be created automatically
Printing Program Memory Addresses cs240@data ~/2014Fall/LectureNotes/test $ ./test1 sizeof(int)=4 sizeof(long)=8 sizeof(int*)=8 (TEXT) main=0x4005bc
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 *
Simple Memory Dump of a Program cs240@data ~/2014Fall/lab2 $ gcc -o hintdump hintdump.c cs240@data ~/2014Fall/lab2 $ ./hintdump 0x00007FFF150B1A9C:
Examining the memory of the program: cs240@data ~/2014Fall/lab2/lab2-src-sol $ cat mem.c #include <stdio.h> #include <string.h> #include &
Examining the memory of the program: x.a = 'A'; x.i = 9; x.b = '0'; x.p = &x.i; strcpy(str, "Hello world\n"
Examining the memory of the program cs240@data ~/2014Fall/lab2/lab2-src-sol $ ./mem &str=0x7FFFCFB29B50 &a=0x7FFFCFB29B4C &b=0x7FFFCFB29B4
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
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
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
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
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
Stepping Through your Program Your program will start running and when it reaches “main()” it will stop. gdb> Now you have the following commands
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
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
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.
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
Exiting gdb The command “quit” exits gdb. (gdb) quit The program is running. Exit anyway? (y or n) y
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.
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
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
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
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
Structure of a C program A C program is a sequence of definitions of functions, and global variables, type definitions and function prototypes: glob
Compiling from multiple files Compiling object files: You may compile each file separately and then link them: gcc –c sum.c - Generates sum.
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
Making functions private You can make a function private to a file by adding the static keyword before the function declaration. static void mylocal
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
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
Global Variables in Multiple Files sum.c: extern int total; // extern declaration void sum( int a, int b) { total = a + b; } main.c: #include <
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.
Local Vars Example #include <stdio.h> int fact(int n) { int val; printf("fact(%d)\n", n); if (n == 1) { mymemdump(stdout,
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
Grading Grade allocation Midterm: 25% Final: 25% Projects: 50% Exams will include programming questions.
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
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
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
Implementation of strcpy using array operator. char * strcpy(char * dest, char * src) { int i = 0; while (src[i] != ‘\0’) { dest[i] =
Implementation of strcpy using pointers Implementation of strcpy using pointer operations. char * strcpy(char * dest, char * src) { char * p = sr
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
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:
Implementation of strlen char * strlen(char * src) { int i = 0; while (src[i] != ‘\0’) { i++; } return i; }
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
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*
Course Contents C development cycle: C Programming Structure Control Flow While/for/do, etc Functions Arrays & Strings Pointer Dy
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
Lexical Structure of C A program is a sequence of characters in a text file. hello.c |*...*| int main() { printf(“He
Comments in C Comments /*...*/ same as Java //... available in most compilers but it is not in standard.
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
Keywords Special keywords. while,break, for, case, break,continue, int...
Types of variables int a; // Signed Integer 4 bytes long b; // Signed integer 8 bytes short s; // Signed integer 2 bytes char c; // S
Types of variables float ff; // Floating Point number 4 bytes double dd; // Floating Point number 8 bytes long double ddd; // Floating Point 1
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
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
The Main Program Execution starts in main int main(int argc, char**argv){ } or int main(){ } argc-store # of args. a
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
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
Integer Constants You can add suffix to force type 123456789L → long 55u → unsigned int 234Lu → unsigned long
Floating Point Constants 3.14 → type is always double To force the type float, add “f” suffix. 3.14f → float constant
Character constant 'q' enclosed with a single quote. Also you can use escape sequences with '\octal number' e.g. '\020’
Character Constants Also there are some common escape sequences '\n' → new line '\r' → return '\t'
Character Constants Character constants have type int. int i; i = 'A'; //assign ascii 65 to I Or i = 65; printf(“A = %d\n”, &apo
String Constants “My String” is a string constant of type (char *) There are no operations with string in Java like “Hello”+”world”. However, t
Short-Circuit && (and) and || or expression e1 && e2 is the short circuit “and” expression If e1 is false, e2 is not evaluated.
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
Conditional Expressions e = (e1 ? e2 : e3) *conditional expression Equivalent to if(e1){ e = e2; }
Comments to this Manuals