[英]Segmentation fault when using malloc and realloc with arrays
I'm fairly new to c and I'm trying to understand and grasp malloc. 我对c还是很陌生,我试图理解和掌握malloc。 My program takes an integer x input, then loops until x is met while also taking other integer inputs.
我的程序接受一个整数x输入,然后循环直到满足x,同时也接受其他整数输入。 I then do various calculations.
然后,我进行各种计算。 However I'm getting a segmentation fault and I don't understand why.
但是我遇到了细分错误,我不明白为什么。
#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++;
}
}
The problem is with 问题出在
scanf("%d", &array[i])
where, the value of i
is indeterminate. 其中,
i
的值不确定。
To elaborate, i
is an uninitialized local variable and unless initialized explicitly, the contents remain indeterminate. 详细地说,
i
是一个未初始化的局部变量,除非明确初始化,否则内容仍然不确定。 Attempt to use that value, in this scenario, would lead to invokes undefined behavior . 在这种情况下,尝试使用该值将导致调用未定义的行为 。
Even if you initialize i
, you never operated on i
, so all the changes will be overwritten on a fixed index. 即使初始化
i
,也不会对i
操作,所以所有更改都将被覆盖在固定索引上。 You got to take care of this case, too. 您也必须处理此案。
Solution: Looking at the code, it appears, you may want to use 解决方案:查看代码,它可能会出现,您可能想使用
scanf("%d", &array[c]);
instead. 代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.