I wrote an function which should realloc the array for each input. I think that function works well, but when I'm trying to work with the array I got segmentation fault.
Input:
[1,2] [6,3] [2.5,3.5]
I have to check if the user enters input in the correct form '[' number ',' number ']'
. I have to have at least 2 entries. The end of input isn't new line, but EOF (CTRL+D or CTRL+Z).
My code:
double ** allocation (double ** field, int i)
{
double x = 0, y = 0;
char obr[1], cbr[1], col[1];
while (scanf("%c%lf%c%lf%c", &obr, &x, &col, &y, &cbr) == 5)
{
if (col[0] != ',' || obr[0] != '[' || cbr[0] != ']')
return 0;
field = (double **) realloc(field, (i + 1) * sizeof(*field));
if (field == NULL)
return 0;
field[i] = (double *)malloc(2 * sizeof(double));
if (field[i] == 0)
return 0;
field[i][0] = x;
field[i][1] = y;
i++;
}
if (feof (stdin))
return 0;
return field;
}
And when I want to use this:
double min = sqrtf(powf(field[0][0] - field[1][0], 2) + powf(field[0][1] - field[1][1], 2));
I will get my segmentation fault.
From
man realloc
(emphasis mine):You're not guaranteed to be using the same memory when you use
realloc
, you need to pass the pointer back for the case that it's been moved to a new location. You can check for success by checking whether it's a NULL pointer or not, too.tl;dr: You need to use
return field
instead ofreturn 1
orreturn 0
.