【发布时间】: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 抱歉,我忘了发布我的缩进代码。我现在已经编辑过了。