170 likes | 199 Views
Common bugs. CS 2204 Class meeting 10. Example 1. TYPE: Accidental for (i=0; i<numrows; i++) for (j=0; j<numcols; j++); pixels++;. Example 2. TYPE: Missing or improper initialization int minval(int *A, int n) { int currmin; for (int i=0; i<n; i++) if (A[i] < currmin)
E N D
Common bugs CS 2204 Class meeting 10
Example 1 • TYPE: Accidental for (i=0; i<numrows; i++) for (j=0; j<numcols; j++); pixels++;
Example 2 • 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; }
Example 3 • 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; }
Example 4 • TYPE: copy and paste bug switch (i) { case 1: do_something(1); break; case 2: do_something(2); break; case 3: do_something(1); break; case 4: do_something(4); break; default: break; }
Example 5 • TYPE: Accidental if (foo = 5) foo == 7;
Example 6 • 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(); }
Example 7 • 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);
Example 8 • TYPE: model error char* string1 = "Hello"; char* string2 = "World"; if (string1 == string2) do_something();
Example 9 • TYPE: Memory Error int i; char string[5] = "hello"; int j;
Example 10 • TYPE: Memory error char* ptr; cin >> ptr;
Example 11 • TYPE: Off-by-one error int i; int array[5]; int j; for (i=0; i<=5; i++) cin >> array[i];
Example 12 • TYPE: Special case error // Delete the node following the one that ptr is // pointing at. void del_link(lnode* ptr) { ptr->next = ptr->next->next; }
Example 13 • TYPE: Stack frame error char *initialize() { char string[80]; char* ptr = string; return ptr; } main() { char *myval = initialize(); do_something_with(myval); }
Example 14 • TYPE: Stack frame error char* assign() { return "hello world!"; } main() { char *ptr = assign(); }
Example 15 • 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; }