I'm fairly new to c and I'm trying to understand and grasp malloc. My program takes an integer x input, then loops until x is met while also taking other integer inputs. 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.
To elaborate, i
is an uninitialized local variable and unless initialized explicitly, the contents remain indeterminate. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.