c - malloc 上的段错误

标签 c segmentation-fault malloc

我正在从一个文件中读取整数,当我尝试增加我的数组时,我在 second 调用 growMyArray(struct myArray) 时遇到段错误,特别是在 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;
}

我的结构:

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

从输入重定向读取:

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;
}

我觉得这特别奇怪,因为增长数组在第一次总是有效,但在第二次就永远无效。我为 DEFAULT_SIZE 使用了多个值,在一组大小为 200000 的测试数据上,范围从 2 到 20000。

second 调用 growMyArray 时出现段错误是否有明显的原因,特别是在 int *grownArray = malloc(arrayToGrow.maxCount * sizeof(int));?

最佳答案

你写的超过了数组的末尾。

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

    randomNumbers.count++;

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

因为您在测试中使用了 >if 仅触发一次 randomNumbers.count = randomNumbers.maxCount + 1,即 scanf 写入数组末尾之后的 randomNumbers.numbers[randomNumbers.maxCount]

因此,在 if 语句中将 > 更改为 >=

关于c - malloc 上的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12901967/

相关文章:

c - 在没有 malloc 的情况下进入 char *str,没有段错误?

c - 为什么人们要定义自己的 offsetof?

c - 使用 malloc、struct 和 char * 的堆损坏

linux - Android Studio/SDK : platform-tools (adb, fastboot)出现段错误(Gentoo Linux)

c++ - segmentation 故障的常见原因的明确列表

c - 函数中的 Malloc 和 free(优化你的内存)

c - Arduino MIDI Controller menuUsed 未在此范围内声明

c - 打印 char* 导致段错误?

c++ - 只有当您按回车键或到达文件末尾时,函数才会导致段错误

C - 扫描动态二维字符数组并进行分配