Question: The following program (also available as cubes.c in the lab3 directory on your code-server IDE) should print the sum of the first n positive cubes,

The following program (also available as cubes.c in the lab3 directory on your code-server IDE) should print the sum of the first n positive cubes, i.e., 13+23+33+...+3 where n is a positive integer passed to the program as a command line argument. Unfortunately the program has several bugs and leaks memory. You need to fix the bugs so that the program outputs the correct sum. Additionally, you should fix all leaks and memory access errors reported by valgrind. The program should be fixable with only a few small modifications, do not rewrite the entire program from scratch. For example: Test Result ./cubes 1 total: 1 ./cubes 2 total: 9 ./cubes 3 total: 36

#include #include #include

/* This program should print the sum of the first n positive cubes * 1^3 + 2^3 + 3^3 + ... + n^3 * where n is a positive integer read from the input * 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, total; for(i = 0; i => total += arr[i]; }

/* Fills the given array with the values * 1^3, 2^3, 3^3, ..., (n-1)^3, n^3. */ void fillCubes(int n, int arr[]) { int i; for(i = 1; i => arr[i] = i*i*i; }

/* Takes a positive integer n from the command line, * fills array with first n cubes, then computes * the sum of the cubes. Prints out the * sum before freeing all used memory. If no command * line argument is given prints a message on how * the program should be run. */ int main(int argc, char* argv[]) { int n, total; int* arr;

if(argc printf(\"usage: %s n \", argv[0]); return 1; }

// convert the first argument from a string to a number n = atoi(argv[1]); assert(n > 0);

arr = malloc(n);

fillCubes(n, arr); total = sum(n, arr); printf(\"total: %d \", total);

free(arr); return 0; }

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 Programming Questions!