Realloc double 2D array in C

2019-07-24 17:09发布

问题:

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.

回答1:

From man realloc (emphasis mine):

The realloc() function tries to change the size of the allocation pointed to by ptr to size, and returns ptr. If there is not enough room to enlarge the memory allocation pointed to by ptr, realloc() creates a new allocation, copies as much of the old data pointed to by ptr as will fit to the new allocation, frees the old allocation, and returns a pointer to the allocated memory.

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 of return 1 or return 0.