Search code examples
cpointersloopsfwrite

Last value in pointer memory is incorrect


The program is long(here is the full version: http://pastebin.com/cvg1eSJ1), (sample.txt looks like this: http://pastebin.com/hWihPpSj, it is the INPUT file, and another command line argument is the output file.) but I am posting the parts dealing with the 'second pointer list'. Essentially I have a list of 47 or so items, and I need to add items outside of a certain range to a second list. This is where I first save the values. I use "tempAddress" just to clean up the code some. I just take the value at the current address, check it, and if it matches then add it to the second Reading List.

    for (i; i < numElements; i++) {
        tempAddress = firstReadingList++;
        if ((double) *tempAddress > plusOutlier || (double) *tempAddress < minusOutlier) {
            *secondReadingList++ = *tempAddress;

            numOutliers++;
            printf("%d ", *tempAddress);
        }
    }

Later on, I have to write this reading list in another function to a file. I print out the values, and ONLY the last value is incorrect. I have no idea why. Here is the code where I write them to the file(tempAddress is a new variable in this case)

for (i; i < numElements; i++) {
    tempAddress = (outlierList + i);
    printf("%d ", *tempAddress);
    fprintf(out, "%d ", *tempAddress);
}

The output in the first function is as follows:

752 843 840 848 752 850 753 (this is correct)

The second code snippit outputs this

752 843 840 848 752 850 577 (577 is incorrect)

Did I do something wrong? I'm still relatively new to pointers. I DO NOT modify the secondListPointer at any point between functions.


Solution

  • Before you call get_outliers, you allocate memory for one int:

    int *outlierList = malloc(sizeof *outlierList);
    
    int numOutliers = get_outliers(dataPointer, numReadings, outlierList, average, stdDev, STDDEV_SCALAR);
    

    but there may be more than one outlier. Then you write outside the allocated memory, invoking undefined behaviour, with unforeseeable consequences. Here, just some data was corrupted.