[英]Segmentation fault when using malloc and realloc with arrays
我對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++;
}
}
問題出在
scanf("%d", &array[i])
其中, i
的值不確定。
詳細地說, i
是一個未初始化的局部變量,除非明確初始化,否則內容仍然不確定。 在這種情況下,嘗試使用該值將導致調用未定義的行為 。
即使初始化i
,也不會對i
操作,所以所有更改都將被覆蓋在固定索引上。 您也必須處理此案。
解決方案:查看代碼,它可能會出現,您可能想使用
scanf("%d", &array[c]);
代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.