简体   繁体   中英

Seg fault on malloc

I am reading integers from a file, and when I try to grow my array, I am getting a segmentation fault on the second call to growMyArray(struct myArray) , specifically at int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int)); :

struct myArray growMyArray(struct myArray arrayToGrow) {

    arrayToGrow.maxCount *= 2;

    int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int));

    int i;
    for (i = 0; i < arrayToGrow.count; i++)
        grownArray[i] = arrayToGrow.numbers[i];

    free(arrayToGrow.numbers);

    arrayToGrow.numbers = grownArray;

    return arrayToGrow;
}

My structure:

typedef struct myArray {
    int count;
    int maxCount;
    int *numbers;
} myArray;

Reading from input redirection:

struct myArray getRandomNumbers() {

    struct myArray randomNumbers;
    randomNumbers.count = 0;
    randomNumbers.maxCount = DEFAULT_SIZE;
    randomNumbers.numbers = malloc(randomNumbers.maxCount * sizeof(int));

    while (scanf("%d", &randomNumbers.numbers[randomNumbers.count]) == 1) {

        randomNumbers.count++;

        if (randomNumbers.count > randomNumbers.maxCount)
            randomNumbers = growMyArray(randomNumbers);
    }

    return randomNumbers;
}

I find this particularly odd because growing the array always works the first time but never works the second time. I have used multiple values for DEFAULT_SIZE , ranging from 2 to 20000 on a set of test data of size 200000.

Is there an apparent reason why I am getting a segmentation fault on the second call to growMyArray , specifically at int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int)); ?

You wrote past the end of the array.

while (scanf("%d", &randomNumbers.numbers[randomNumbers.count]) == 1) {

    randomNumbers.count++;

    if (randomNumbers.count > randomNumbers.maxCount)
        randomNumbers = growMyArray(randomNumbers);
}

Because you use > in the test, the if only fires once randomNumbers.count = randomNumbers.maxCount + 1 , ie the scanf writes to randomNumbers.numbers[randomNumbers.maxCount] which is past the end of the array.

Therefore, change > to >= in the if statement there.

take care of youre data type

typedef struct myArray {
    int count;
    int maxCount;
    int *numbers;
} myArray;

this means that count and maxcount are signed integers and they can reach negative values which is not correct for count and can lead also to some memory corruption.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM