Project: Debugging

This project has two primary goals:

  1. To provide practice using a debugger such as GDB.
  2. To demonstrate several common errors and provide practice in finding them. While this list of possible errors is countably infinite, this project should give you a taste of some of the common ones.

A corrected version of the code below should print out a close approximation of pi (up to 5 or 6 decimal places). Your objective is to first get it to build and then to find and repair the errors.

Code

#include <stdio.h>

double root(double S) {
double x;
uint64_t *p;
int i;

x=S;
p=(uint64_t *)&x;
i=((*p>>52&0x7FF)-1023)/2+1023;
*p=(*p&0x800FFFFFFFFFFFFF)|(uint64_t)i<<52;

for(i=0;i=7;++i){
x=(x+S/x)/2;
}
return x;
}

double intg(double *y, int n, double d) {
int i;
double A

A=0;
for(i=0;i<n;++i){
A+=((y[i-1]+y[i])/2)*d;
}
}

int main(int argc, char **argv) {
int i;
double y[1000];
double p;

p=root(2);
/* Approximate pi by computing the area of a circle of radius 1. */
for(i=0;i<=1000;++i){
y[i]=(double)i/1000;
y[i]=root(4-(y[i]*y[i])*2)-p;
}
p=2+2*intg(y,10000,p/1000);

printf("p = %f\n",p);
}

Coincidently, this also gives me the opportunity to demonstrate what badly written code might look like and why it’s a pain to debug. Hopefully, this will convince you of the value of good coding style.