【问题标题】:Segmentation fault when using malloc and realloc with arrays对数组使用 malloc 和 realloc 时出现分段错误
【发布时间】:2017-03-01 18:26:35
【问题描述】:

我对 c 还很陌生,我正在尝试理解和掌握 malloc。我的程序接受一个整数 x 输入,然后循环直到满足 x ,同时还接受其他整数输入。然后我做各种计算。但是我遇到了分段错误,我不明白为什么。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(void)
{

    calculations();
}

void calculations()
{

    int i;
    int x;
    int total = 0;
    double squareRoot;
    double overall;

    scanf("%d", &x);

    int* array = malloc(x * sizeof(int));

    if (!array) {
        printf("There isn't enough memory \n");
        return;
    }

    int c = 0;

    while (c < x) {

        scanf("%d", &array[i]);

        total = array[i] * array[i];
        c++;
    }

    squareRoot = sqrt(total);
    array = realloc(array, x * sizeof(int));

    int b = 0;

    while (b < x) {

        overall = array[i] / squareRoot;
        printf("%.3f ", overall);

        b++;
    }
}

【问题讨论】:

  • 你有调试器吗?这会告诉你哪一行触发了分段错误。
  • 奇怪的对齐和缺少缩进是怎么回事?
  • array = realloc(array, x* sizeof(int)); 中,如果您打算扩展 - 然后索引 - 内存分配,它不会提供更多内存,与原始 @987654323 的分配相同 @
  • Valgrind 将帮助您缩小此类内存访问错误的范围。
  • @SouravGhosh 抱歉,我忘了发布我的缩进代码。我现在已经编辑过了。

标签: c arrays


【解决方案1】:

问题出在

 scanf("%d", &array[i])

其中,i 的值是不确定的。

详细地说,i 是一个未初始化的局部变量,除非显式初始化,否则内容仍然不确定。在这种情况下,尝试使用该值会导致调用 undefined behavior

即使你初始化了i,你也从来没有对i进行过操作,所以所有的改变都会覆盖在一个固定的索引上。你也得处理好这个案子。

解决办法:看代码,出现了,你可能要使用

scanf("%d", &array[c]);

改为。

【讨论】:

  • 感谢这解决了我的问题!我将所有 array[i] 更改为 array[c] 但是当我现在运行我的程序时,我只得到 0.000 作为我的输出?知道这是为什么吗?
猜你喜欢
  • 1970-01-01
  • 2021-06-28
  • 2017-06-06
  • 2018-09-24
  • 2021-03-04
  • 2021-03-18
  • 1970-01-01
  • 2015-01-27
相关资源
最近更新 更多