Search code examples
c++pointersdereferencesegmentation-fault

sigsegv error in aggregate method


Here is my code:

#include <cstdlib>
#include <stdio.h>
#define NUM_READINGS 3
int* readingsTotal;
int* readingsAverage;
int readingsIndex;

using namespace std;

void avgOf(int* toFindAvgOf, int size) {
    int i;
    for (i = 0; i < size; i++) {
        // Add reading to total for each component.
        readingsTotal[i] += toFindAvgOf[i];
        // Once method has been iterated through n (NUM_READINGS) times:
        if (readingsIndex == NUM_READINGS - 1) {
            // Set the arithmetic mean.
            readingsAverage[i] = readingsTotal[i] / NUM_READINGS;
            // Reset the total.
            readingsTotal[i] = 0;
        }
    }
    readingsIndex++;
}

int iterate(int findAvgOf) {
    int toFindAvgOf[] = {findAvgOf, 20, 30};
    avgOf(toFindAvgOf, sizeof (toFindAvgOf));
    return readingsAverage[0];
}

int main(int argc, char** argv) {

    readingsTotal = (int []){0, 0, 0};
    readingsAverage = (int []){0, 0, 0};
    int i;
    for (i = 0; i < 3; i++) {
        int smthd = iterate(12 + i * 2);
        printf("%d\n", smthd);
    }
    return 0;
}

When I run this in netbeans c/c++, it builds with now errors but when it executes it fails and prints:

RUN FAILED (exit value 1, total time: 86ms)

When I go into debug mode it also fails immediately and gives the SIGSEGV error. From reading online I'm guessing there is some issue with the way I am dereferencing a pointer. But I have no clue where exactly it is failing at. I am pretty new to c++ so any help would be great!


Solution

  • In C, the sizeof function returns the size of the object in bytes.

    So when you say: sizeof (toFindAvgOf)

    That will return 12 (assuming an int on your system is 4-bytes) thus causing an index out of bounds condition in the avgOf function.

    To get the length of the array:

    sizeof(toFindAvgOf) / sizeof(int)