0

I have a pretty basic question, I tried to answer it for many hours now but it still doesn't work. I want to malloc an array in main, pass it to another function, reallocate it and then change it's values. Why does the following code work:

void fun(int **array, int *size) {
    *array = (int *) realloc(*array, *size * sizeof(int));
    *array[0] = 1;
  
    return;
}

int main() {
    int size = 5;
    int *array = (int *) malloc(2 * sizeof(int));
    fun(&array, &size);
  
    return 0;
}

... but as soon as I try to change array[1] like this:

void fun(int **array, int *size) {
    *array = (int *) realloc(*array, *size * sizeof(int));
    *array[0] = 1;
    *array[1] = 2;

    return;
}

int main() {
    int size = 5;
    int *array = (int *) malloc(2 * sizeof(int));
    fun(&array, &size);
  
    return 0;
}

... it doesn't work anymore. It gives me segmentation fault and invalid write of size 4.

1
  • 4
    *array[0]: Check operator precedence, should be (*array)[0]. Commented Oct 22, 2021 at 6:17

1 Answer 1

2

In *array[0] = 1;, the []operator has highest precedence, meaning it's interpreted as first doing pointer arithmetic on a int**, then de-reference it. It's equivalent to **(array + 0) = 1 which is not what you want.

For a single-dimension array you can simply do this:

#include <stdlib.h>

void fun (int** array, int size)
{
  int* tmp = realloc( *array, sizeof(int[size]) );
  if(tmp == NULL)
  {
    // error handling here
  }
  *array = tmp;

  (*array)[0]=1;
  (*array)[1]=2;
}

int main (void)
{
  int* array = malloc(2*sizeof *array);
  int size = 5;
  fun(&array, size);

  free(array);
  return 0;
}

For multiple dimensions, check out Correctly allocating multi-dimensional arrays

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.