0
#include <stdio.h>

void avg_sum(double a[], int n, double *avg, double *sum)
{
    int i;
    sum = 0;
    printf("%f", *sum);
    for(i=0; i<n; i++)
        *sum += a[i];
    *avg = *sum/n;
}


int main()
{
    double arr[2] = {0.0,1.0};
    double *sum;
    double *avg;
    int n = 2;
    avg_sum(arr, n, avg, sum);
    printf("...Done...\n");
    
    return 0;
}

Tried using both GCC(https://www.tutorialspoint.com/compile_c_online.php) and clang(from repl.it) online compilers

2 Answers2

1

Easy. In line 6 you assign 0 to sum but sum is not the actual sum but a pointer to it. When you try to print it you access invalid memory.

Edit: BTW if you try compling with -fanalyzer you will get a warning and an explanation. https://godbolt.org/z/W6ehh8

1
double *sum;

This creates a pointer to a double but it has an arbitrary value and therefore points at no dedicated memory.

In addition, in the called function, you set the sum pointer to zero (the null pointer) then try to use that pointer to dereference memory - that's a big non-no.

I'd also be wary of for(i=0; i<n-2; i++) for summing the values in the array. It's not going to include the final two which, since n is two, means it won't accumulate any of them.

The correct way to do this would be with:

void avg_sum(double a[], int n, double *avg, double *sum) {
    int i;
    *sum = 0;               // set content, not pointer.
    for(i=0; i<n; i++)      // do all elements.
        *sum += *(a+i);
    *avg = *sum/n;
}

int main(void) {
    double arr[2] = {0.0,1.0};
    double sum;                  // ensure actual storage
    double avg;                  // and here
    int n = 2;
    avg_sum(arr, n, &avg, &sum); // then pass pointers to actual storage

    printf("Sum=%f, Avg=%f\n", sum, avg);
    
    return 0;
}

This gives you, as expected:

Sum=1.000000, Avg=0.500000
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953