Question: use Valgrind to troubleshoot it. Fix the code below; The code was intended to compute the average grade for a defined number of students. Each

use Valgrind to troubleshoot it.

Fix the code below; The code was intended to compute the average grade for a defined number of students. Each grade is supposed to be between 0 and 100. For some reason, the computed average isnt correct. Use Valgrind and your troubleshooting skills to fix this code. Valgrind usage: valgrind a.out Once the code is working properly, the final line of the Valgrind output should say that there are 0 errors and the LEAK SUMMARY should show 0 bytes lost.

/* Sample code to be used with Valgrind Memory Debugger Written by Justin Goins This code has bugs! */ #include  #include  using namespace std; #define NUMSTUDENTS 15 /* This function accepts a pointer to a double (which will be set to the average), a pointer to an array, and an int with the number of items in the array. */ void calculate_average(double* result, int* array, int num) { cout << "Calculating the average value... " << endl; int sum = 0; for (int i = 1; i <= num; i++) { cout << "Grade " << i << ": " << array[i] << endl; sum += array[i]; } //cout << "Sum: " << sum << endl; *result = (double)sum/num; //cout << "Result: " << *result << endl; } /* This program is designed to calculate the average of an array of values. */ int main() { int* grades = new int[NUMSTUDENTS]; double* average = new double; // fill the grades with random values srand(time(0)); for (int i = 0; i < NUMSTUDENTS; i++) { grades[i] = rand() % (100 + 1); } calculate_average(average, grades, NUMSTUDENTS); cout << "The calculated average is: " << average << endl; // clean up the dynamic memory delete[] grades; 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 Databases Questions!