-2

I need to sum, then find their average to calculate the variance of columns or rows of a matrix. I started writing the function from the column part. I wrote the sum as a for loop, but it just keeps giving -431602080.00. Here's my function:

float variance(float **varianceMatrix, int varianceRow, int varianceColumn, char
varianceSelector)   
{ 

int a, i, b;
float *varianceSum, *varianceAvg, *varianceNew;
int selectedColumn;

printf("%d rows, %d columns, %c is selected.\n", varianceRow, varianceColumn, varianceSelector);

switch(varianceSelector)
{
case 'c':

    varianceSum = (float*)malloc(varianceColumn*sizeof(float));
    varianceNew = (float*)malloc(varianceColumn*sizeof(float));
    varianceAvg = (float*)malloc(varianceColumn*sizeof(float));

    for(b = 0; b < varianceColumn; b++)
    {
        for(a = 0; a < varianceRow; a++)
            {
                varianceSum[a] += varianceMatrix[a][b]; 
            }
    }

    printf("Sum array:\n");
    for(a = 0; a < varianceColumn; a++)
    {
        printf("%f\n", varianceSum[a]);
    }

    for(a = 0; a < varianceColumn; a++)
    {
        varianceAvg[a] = varianceSum[a] / varianceRow;
    }

    for(a = 0; a < varianceColumn; a++)
    {
        printf("%d. rows average value: %d\n", a+1, varianceAvg[a]);
    }

}

}

2 Answers2

2

The problem occurs because you don't initialize values of the malloc'ed arrays. Also, it looks like you have a buffer overrun in the nested loop. Here's the fixed code:

for(b = 0; b < varianceColumn; b++)
{
    varianceSum[b] = 0;
    for(a = 0; a < varianceRow; a++)
    {
        // Using varianceSum[a] causes a buffer overrun

        // Assuming that you need to work out
        // sum of the matrix's columns
        varianceSum[b] += varianceMatrix[a][b]; 
    }
}
Eldar Dordzhiev
  • 5,105
  • 2
  • 22
  • 26
1

varianceSum[a] is not initialised. The line:

    varianceSum[a] += varianceMatrix[a][b];

is causing your bug.

You can use calloc() which initialises varianceSum to zero.

user12205
  • 2,684
  • 1
  • 20
  • 40
  • I upped, because I love calloc and hate varargs (one of the nerdiest things that I will say today) but you should mention that it needs to be matched with free... and pedantic a-holes will also mention that you should check the return value... – Grady Player Dec 21 '14 at 18:18
  • True. But these problems already exist in OP's code with `malloc()`. I'm only stating in the answer what's causing OP's bug. – user12205 Dec 22 '14 at 03:29