Development Debugging CS 2204 Class meeting 9 10
Development: Debugging CS 2204 Class meeting 9 -10 *Notes by Mir Farooq Ali and other members of the (C) Doug. Tech. Bowman, Virginia Tech, CS faculty at Virginia Copyright 2001 -2003. 2001
Example 1 n TYPE: Accidental for (i=0; i<numrows; i++) for (j=0; j<numcols; j++); pixels++; 2
Example 2 n TYPE: Missing or improper initialization int minval(int *A, int n) { int currmin; for (int i=0; i<n; i++) if (A[i] < currmin) currmin = A[i]; return currmin; } 3
Example 3 n TYPE: Dyslexic int minval(int *A, int n) { int currmin = MAXINT; for (int i=0; i<n; i++) if (A[i] > currmin) currmin = A[i]; return currmin; } 4
Example 4 n TYPE: copy and paste bug switch (i) { case 1: do_something(1); case 2: do_something(2); case 3: do_something(1); case 4: do_something(4); default: break; } break; 5
Example 5 n TYPE: Accidental if (foo = 5) foo == 7; 6
Example 6 n TYPE: Abused global int i = 5; int j; int foo(int j) { for (i=0; i<j; i++) do_nothing(); return j; } void ineedj(void) { cout << "j is " << j << "n"; } main() { int j; j = foo(i); ineedj(); } 7
Example 7 n TYPE: Macro bug // random returns a random (positive) integer. // Random returns a random integer in the range 0 // to n-1. #define Random(n) random()%n val = Random(j-i+1); 8
Example 8 n TYPE: model error char* string 1 = "Hello"; char* string 2 = "World"; if (string 1 == string 2) do_something(); 9
Example 9 n TYPE: Memory Error int i; char string[5] = "hello"; int j; 10
Program memory 11
Example 10 n TYPE: Memory error char* ptr; cin >> ptr; 12
Example 11 n TYPE: Off-by-one error int i; int array[5]; int j; for (i=0; i<=5; i++) cin >> array[i]; 13
Example 12 n TYPE: Special case error // Delete the node following the one that ptr is // pointing at. void del_link(lnode* ptr) { ptr->next = ptr->next; } 14
Example 13 TYPE: Stack frame error n char *initialize() { char string[80]; char* ptr = string; return ptr; } main() { char *myval = initialize(); do_something_with(myval); } 15
Example 14 n TYPE: Stack frame error char* assign() { return "hello world!"; } main() { char *ptr = assign(); } 16
Example 15 n TYPE: Static Vs dynamic data main() { Record city; lnode *list = NULL; while (data_to_read()) { Readin_data(&city); insert(&city, &list); } } void insert(Record*& city, lnode*& list) { lnode* ptr = new lnode; ptr->next = list; list = ptr; prt->data = city; } 17
- Slides: 17