Question: DEBUG THE FOLLOWING C PROGRAMS: SQUARES.C: #include /* This program should print the sum of the elements * 1^2, 2^2, 3^2, ..., n^2 * where

DEBUG THE FOLLOWING C PROGRAMS:

DEBUG THE FOLLOWING C PROGRAMS: SQUARES.C: #include /* This program should print

SQUARES.C:

#include

/* This program should print the sum of the elements

* 1^2, 2^2, 3^2, ..., n^2

* where n is an integer provided by the user on the

* command line. Hunt down the bugs and squash them!

* Seek out the memory leaks and plug them up! */

/* Computes the sum of the first n elements in the array. */

int sum(int n, int* arr) {

int i, sum;

for(i = 0; i

sum += *(arr+i):;

}

/* Fills the given array with the values

* 1^2, 2^2, 3^2, ..., (n-1)^2, n^2. */

void fillSquares(int n, int* arr) {

int i;

for(i = 1; i

arr[i] = i*i;

}

/* Reads an integer n from arguments,

* fills array with squares, and computes

* the sum of the squares. Prints out the

* sum before freeing all used memory. */

int main(int argc, char* argv[]) {

int n, total;

int* arr;

if(argc

printf("usage: ./squares n ");

return 1;

}

n = atoi(argv[1]);

arr = (int*) malloc(n);

fillSquares(n, arr);

total = sum(n, arr);

printf("total: %d ", total);

return 0;

}

String.c:

#include

#include

#include

#define BLOCKSIZE 4096

/* Don't worry about what this program does. Just fix

* the bugs and memory errors/leaks! And don't drastically

* modify the code... */

char* make_copy(int i, char* string) {

size_t len;

char *s;

len = strlen(string);

s = (char*)malloc(sizeof(char)*len);

strncpy(s, string, len);

s[len] = '\0';

if( !(i%1000) )

printf("i=%d, %s ", i, s);

}

main() {

int i;

char *ptr, *string = "find the bugs!";

ptr = (char*)malloc(BLOCKSIZE);

for(i=0; i

strcpy(ptr, string);

make_copy(i, ptr);

}

}

1. Use gdb and valgrind to find and correct all of the bugs in squares.c and strings.c. You may need to look at the man pages for any library functions used in the code to ensure they are being used correctly. Describe all of the bugs you identify in a file called README you create in the lab4 directory

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!