Question: Skeleton Code: #include #include #include using namespace std; // sum an array of numbers int test1(int *data, int len) { int sum = 0; for(int
Skeleton Code:
#include
// sum an array of numbers int test1(int *data, int len) { int sum = 0; for(int i=0; i
// Allocate a random number array char* test2_init(int len) { char buf[80]; cout > buf; char* mydat = new char[strlen(buf)+1]; strcpy(mydat, buf); return mydat; }
char* test2_reverse(char* word) { int len = strlen(word); char* otherword = new char[len+1]; for(int i=0; i
int main(int argc, char* argv[]) { if(argc
if(test == 1){ // Test should sum up the array values and print it int *data = new int[len]; for(int i=0; i
else if(test == 2){ // Test should create a random string & then reverse a copy char* myword = test2_init(len); cout
return 0; }


4.4 Fixing Valgrind Errors A program memleak.cpp is included with the files this week. It basically contains two different tests, both of which have bugs. Build and run it (your input in bold italics): $ ./compile memleak $ . /memleak 1 Test 1 sum is 475 $ . /memleak 2 Enter a word: rutabaga Both of these tests are wrong, but you will now fix them IMPORTANT: For all of the bugs you fix in this part of the lab, you have to keep some documentation of what bugs you find and what you change to fix them. This is mandatory because you will review with your CP/TA when you "check in." We recommend that you: prominently write comments in your code indicating each line you change and why you changed it keep a separate list somewhere of the chronological order of changes (was it for memleak 1 or memleak 2?) to guide your discussion with the CP/TA . 1. Run the 1st test: $ ./memleak1 This program is supposed to be adding up 7 random numbers between 0 and 99 and printing out the sum. However, now let's see if there are any hidden memory issues. Let's run valgrind: valgrind --tool-memcheck -1eak-check-yes ./memleak 1 You should see 2 errors (an Invalid Read and a block of memory that is definitely lost). An invalid read means you are trying to access a piece of memory that is not allocated to you. Usually it's because you have a bad pointer or access things beyond the end of an array. Use the line numbers in the error messages as clues and try to fix the code (Google the error message if you are having trouble understanding it) Recompile memleak. cpp and rerun valgrind until you have 0 errors
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
