Home > Net >  Double an array dynamically
Double an array dynamically

Time:10-25

I am trying to solve the following exercise in C:

"Consider a function dobuleArray() that takes in input an array and a pointer to its size and gives as output the array doubled. Create an array of size 1 to 4 as initial size. Then, start filling the array with 2048 randomly generated integers; each time the array is full, call the doubleArray() ​ function. After each invocation of ​ doubleArray()​ , print again the content of the array"​

I am having issues with an initial size of 3. The program I have written does not work for number greater then 4 and I do not know why, too. Precisely, I get a realloc: invalid next size

int* doubleArray(int* vect, int* dim) {
  int old_dim = *dim;
  int i;
  int new_dim = old_dim * 2;
  vect = realloc(vect, new_dim * sizeof(int));
  for (i = old_dim; i < new_dim; i  ) {
    vect[i] = 0;
  }
  *dim = new_dim;
  return vect;
}

int main() {
  int n = 3;
  int* size = &n;
  int* arr = malloc(n * sizeof(int));
  for (int i = 0; i < 2048; i  ) {
    if (i > *size) {
      int j = 0;  // used to count the size of the doubled-array each time the
                  // if condition is true
      arr = doubleArray(arr, size);
      for (int i = 0; i < *size; i  ) {
        j  ;
        printf("%d ", arr[i]);
      }
      printf("\n");
      printf("%d\n", j);
      printf("\n");
      arr[i] = rand() % 6;
    } else {
      arr[i] = rand() % 6;
    }
  }
}

The double function should work correctly, I think. The entire program actually works only for values such that 2048 % value == 0. But I guess there should be a way to correct it in order to make it work for 3.

Explicitly, the output from this program looks like:

1 4 3 0 0 0 
6

realloc(): invalid next size
signal: aborted (core dumped)

CodePudding user response:

You write past the end of the array, which causes undefined behavior. (pretty annoying undefined behavior in this case)

    if (i > *size) {

should be

    if (i >= *size) {
  • Related