Question

Fix the code. Use Valgrind to compile below code with no warning and no memory error....

Fix the code. Use Valgrind to compile below code with no warning and no memory error. Also give a comment about how you fix the code.

gcc -std=c99 -pedantic -Wall -Wextra -ftrapv -ggdb3 $* -o question5 question5.c && ./question5

gcc -std=c99 -pedantic -Wall -Wextra -ftrapv -ggdb3 -fsanitize=address -o question5 question5.c && ./question5

Both of these should get the same output .

For example if we input

65535

4

3

2

1

it should give us a output with

What is the maximum number of integers you will provide?
Provide your integers (CTRL-D to end):
Sum of integers is: 10

question5.c

#include
#include
#include

// Calculate the sum of a set of integers

/* checkInput: given the result of scanf check if it
* 0 elements read or EOF. If so exit(1) with a warning.
*
*/
void checkInput(int err) {
if (!err || err == EOF) {
printf("\nInvalid input!\n");
exit(1);
}
}

#define N 4
#define MAXINTS 65535
int main() {
int * bufferHeap = (int*)calloc(N, sizeof(int));
size_t numInts = 0;
printf("What is the maximum number of integers you will provide?\n");
checkInput(scanf("%lu", &numInts));
if (numInts > MAXINTS) {
printf("I think that is too many!\n");
exit(1);
}
if (numInts >= N) {
bufferHeap = (int*)realloc(bufferHeap, sizeof(numInts)* numInts);
}
printf("Provide your integers (CTRL-D to end):\n");
for (unsigned int i = 0; i < numInts; i++) {
int newInt = 0;
int ret = scanf("%d", &newInt);
if (!ret) {
printf("\nInvalid input!\n");
exit(1);
}
if (ret == EOF) {
break;
}
bufferHeap[i] = newInt;
}
  
long long int sum = 0;
for (size_t i = 0 ; i < numInts; i++) {
sum += bufferHeap[i];
}
printf("Sum of integers is: %lld\n", sum);
free(bufferHeap);
return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1
//change the value of the numInts when EOF or ctrl+d is pressed as when you use EOF the garbage value is still present in the bufferHeap and hence if the final loop runs for all the elements that we were supposed to input then it gives wrong answer as it adds that garbage value as well and hence if using EOF then change the value of EOF to avoid reading garbage value from the bufferHeap



#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// Calculate the sum of a set of integers

/* checkInput: given the result of scanf check if it
* 0 elements read or EOF. If so exit(1) with a warning.
*
*/
void checkInput(int err) {
    if (!err || err == EOF) {
        printf("\nInvalid input!\n");
        exit(1);
    }
}

#define N 4
#define MAXINTS 65535

int main() {
    int *bufferHeap = (int *) calloc(N, sizeof(int));
    size_t numInts = 0;
    printf("What is the maximum number of integers you will provide?\n");
    checkInput(scanf("%lu", &numInts));
    if (numInts > MAXINTS) {
        printf("I think that is too many!\n");
        exit(1);
    }
    if (numInts >= N) {
        bufferHeap = (int *) realloc(bufferHeap, sizeof(numInts) * numInts);
    }
    printf("Provide your integers (CTRL-D to end):\n");
    for (unsigned int i = 0; i < numInts; i++) {
        int newInt = 0;
        int ret = scanf("%d", &newInt);
        if (!ret) {
            printf("\nInvalid input!\n");
            exit(1);
        }
        if (ret == EOF) {
            numInts = i;
            break;
        }
        bufferHeap[i] = newInt;
    }

    long long int sum = 0;
    for (size_t i = 0; i < numInts; i++) {
        sum += bufferHeap[i];
    }
    printf("Sum of integers is: %lld\n", sum);
    free(bufferHeap);
    return 0;
}
Add a comment
Know the answer?
Add Answer to:
Fix the code. Use Valgrind to compile below code with no warning and no memory error....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int...

    Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int *); void replaceAt(int *, int, int); int isEmpty(int *, int); int isFull(int *, int); void removeAt(int *, int); void printList(int *, int); int main() { int *a; int arraySize=0,l=0,loc=0; int choice; while(1) { printf("\n Main Menu"); printf("\n 1.Create list\n 2.Insert element at particular position\n 3.Delete list.\n4. Remove an element at given position \n 5.Replace an element at given position\n 6. Check the size of...

  • What is wrong with the following program? Explain how you will fix it in the code....

    What is wrong with the following program? Explain how you will fix it in the code. #include int main() { int i; int *ptr = &i; scanf("%d", &ptr); printf("The value of i is: %d\n", *ptr); return 0; }

  • This code should exit in 0 is inputed or the code should repeat adding two number...

    This code should exit in 0 is inputed or the code should repeat adding two number if '1' is inputed. What are three logical or/and syntax errors in this code? int choice, numi, num2: Linn printf("Enter a number: "); scanf("%d", &numl); printf("Enter another number: "); scanf("%d", &num2); printf ("Their sum is d\n", (numl+num2)); printf ("Enter 1 to repeat, 0 to exit"); scanf("%d", &choice) } while (choice == 0) HH

  • Programming C....... function code is clear but compile is wrong .. I input 8 and compiled...

    Programming C....... function code is clear but compile is wrong .. I input 8 and compiled 2 0 1 1 2 3 5 8 13.. look first number 2 is wrong. The correct answer 8 is 0 1 1 2 3 5 8 13 21.. Need fix code to compile correctly.. Here code.c --------------------------------------------------------------------------------------------------------------------- #include <stdio.h> #include <math.h> int fibonacciIterative( int n ) { int fib[1000]; int i; fib[ 0 ] = 0; fib[ 1 ] = 1; for (...

  • Fix the code below to make it so that it is not vulernable to stack buffer...

    Fix the code below to make it so that it is not vulernable to stack buffer overflow void gctinp (ohar *inp, int siz) puts ("Input value: ") fgets (inp, siz, stdin) printf("buffer3 getinp read %s\n", inp); void display (char val) char tmp [16]; sprintf(tmp, "read val : puts (tmp); %s\n", val); int main(int argc, char *argv []) char buf [16]; getinp (buf, sizeof (buf)) display (buf); printf ("buffer3 done In")

  • Do you have a flowgorithim flow chart for this code? #include <stdio.h> int main() { int num,i=0,sum=0; float aver...

    Do you have a flowgorithim flow chart for this code? #include <stdio.h> int main() { int num,i=0,sum=0; float average; int customerNumbers[num]; int customerSales[num]; printf("How many customers do you want to track?\n"); scanf("%d",&num); while(i<num) { printf("Enter the customer number. "); scanf("%d",&customerNumbers[i]); printf("Enter the sales for the customer "); scanf("%d",&customerSales[i]); i++; } printf("Sales for the Customer"); printf("\nCustomer Customer"); printf("\nNumber Sales"); for(i=0;i<num;i++) { printf("\n %d \t %d",customerNumbers[i], customerSales[i]); sum=sum+customerSales[i]; } average=(int)sum/num; printf("\n Total sales are $%d",sum); printf("\n Average sales are $%.2f",average); printf("\n --------------------------------------------");...

  • /* •   The following code consists of 5 parts. •   Find the errors for each part...

    /* •   The following code consists of 5 parts. •   Find the errors for each part and fix them. •   Explain the errors using comments on top of each part. */ #include <stdio.h> #include <string.h> int main( ) { ////////////////////////////////////////////////////////////////////////// //////////////        Part A. (5 points)                ////////////////// int g(void) { printf("%s", Inside function g\ n " ); int h(void) {       printf(" % s ", Inside function h\ n "); } } printf("Part A: \n "); g(); printf(" \n"); ////////////////////////////////////////////////////////////////////////// //////////////       ...

  • i need flowchart for the following c code #include <stdio.h> int main() {     int n,...

    i need flowchart for the following c code #include <stdio.h> int main() {     int n, i, sum = 0;     printf("Enter an integer: ");     scanf("%d",&n);     i = 1;     while ( i <=n )     {         sum += i;         ++i;     }     printf("Sum = %d",sum);     return 0; }

  • System Programming in C

    Explain what the problem is within the program. Fix the problem when you create a child process per column. The code is given below. So basically, after the child processes have successfully excuted their code, the final print statement does not give the correct values. It prints the original matrix rather than the multiplied matrix.#include  #include  #include  #include  int main(int argc, char *argv[]){ int row = 0; int column = 0; row = atoi(argv[1]); column = atoi(argv[2]); int *A = ...

  • Convert C to C++ I need these 4 C file code convert to C++. Please Convert...

    Convert C to C++ I need these 4 C file code convert to C++. Please Convert it to C++ //////first C file: Wunzip.c #include int main(int argc, char* argv[]) { if(argc ==1){ printf("wunzip: file1 [file2 ...]\n"); return 1; } else{ for(int i =1; i< argc;i++){ int num=-1; int numout=-1; int c; int c1;    FILE* file = fopen(argv[i],"rb"); if(file == NULL){ printf("Cannot Open File\n"); return 1; } else{ while(numout != 0){    numout = fread(&num, sizeof(int), 1, file);    c...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT