Saturday, March 15, 2008

Spot the Bugs........

Debugging is the systematic process of removing bugs in you program. If these bugs are not removed then it may result in serious damages. Here are some code snippets which consists of a few bugs. Try to debug it without looking at the answers.

Question 1

1    #include "stdio.h"
2
3 #define N 5
4 int Weight[N] = { 3, 1, 4, 5, 2 };
5
6 int rand_choice()
7 {
8 int i, choice = 0;
9 int k = rand() % (3*N);
10 for( i = 0; i <= N; i++ ) 11 {
12 if( k >= 0 ) choice = i;
13 k -= Weight[i];
14 }
15 return choice;
16 }
17 int voting_machine( int vote )
18 {
19 if( vote == 1 ) return rand_choice();
20 else return vote;
21 }

Question 2

1 #include "stdio.h"
2
3 class Animal
4 { public:
5 virtual void init() {}
6 Animal() { init(); }
7 };
8
9 class GroundHog : public Animal
10 { public:
11 const char *appears;
12 virtual void init() { appears = "Feb 2"; }
13 };
14
15 int main()
16 {
17 GroundHog x;
18 printf( "Ground hogs appear %s\n" , x.appears );
19 return 0;
20 }

Question 3


1    #include "stdio.h"
2
3 const int march[31] = {
4 8, 5, 7, 2, -4, -14, -7, -4, -2, 0,
5 0, 2, 5, 7, 2, -4, -14, -7, -4, -2,
6 1, 7, 2, 2, -2, -3, -4, 6, -4, 3, 9 };
7
8 int main()
9 {
10 unsigned i, count = 31;
11 int sum = 0;
12
13 for( i = 0; i < style=""> {
15 sum += march[ i ];
16 }
17 printf( "The average low temperature in March was"
18 " %d degrees\n", sum / count );
19 return 0;
20 }

Question 4

1    #include "stdio.h"
2 class R
3 {
4 public:
5 int k, depth;
6 R() :k(0), depth(0) {}
7 const R& operator=( const R & r )
8 {
9 if( this != &r )
10 { k = r.k; depth = r.depth+1; }
11 return r;
12 }
13 };
14 int main()
15 {
16 R r1, r2, r3;
17 r1 = r2 = r3;
18 printf( "%d %d %d\n",
19 r1.depth, r2.depth, r3.depth );
20 }

Question 5

1    #include "stdio.h"
2 #include "string.h"
3
4 char husband[] = " Charlie";
5 char wife[] = " Sandra";
6
7 char *trim( char *s )
8 { // removing leading blanks
9 char *p = new char[strlen(s)+1];
10 strcpy( p, s );
11 while( *p == ' ' ) p++;
12 strcpy( s, p );
13 delete p;
14 return s;
15 }
16
17 int main()
18 {
19 printf( "...pleased to announce the wedding of"
20 " %s and %s\n", trim(husband), trim(wife) );
21 return 0;
22 }

ANSWERS

1. In line 13, a warning generated for possible access for out of bounds pointer

2. In line 6, a warning is generated for the call of a virtual function 'Animal:init(void)' within a constructor or destructor

3. In line 18, a warning is generated for 'signed-unsigned' mix with divide.

4. In line 11, the assignment operator must return *this

5. In line 13, improper deallocation of the pointer. It should be 'delele []p' instead of 'delete p'

No comments: