Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Design Operation And Evaluation Of Mobile Communications

Authors: Gavriel Salvendy ,June Wei

1st Edition

3030770249, 978-3030770242

More Books

Students also viewed these Programming questions