1

My goal is to dynamically reallocate memory for a two dimensional int array in C. I know there are already several questions about that topic, but unfortunately my code does not run properly and i don't know what is going wrong.

First i am allocating memory:

int n = 10;
int m = 4;
int** twoDimArray;
twoDimArray = (int**)malloc(n * sizeof(int*));
for(int i = 0; i < n; i++) {
   twoDimArray[i] = (int*)malloc(m * sizeof(int));
}

And initializing the array with integer numbers:

for(int i = 0; i < n; i++) {
   for(j = 0; j < 4; j++) {
      twoDimArray[i][j] = i * j;
   }
}

Then i use realloc() to reallocate memory dynamically:

int plus = 10;
int newArraySize = n + plus;
twoDimArray = (int**)realloc(twoDimArray, newArraySize * sizeof(int));

I am expecting my aray twoDimArray to be accessible at [10][0] now, but when running

printf("twoDimArray[10][0] = %d\n", twoDimArray[10][0]);

i get an "EXC_BAD_ACCESS" runtime error.

Probably i am missing something rather simple, but since i am new to C and can't figure out my mistake. Any help is appreciated.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Alienbash
  • 554
  • 7
  • 17

1 Answers1

5

reallocating the array of pointers is necessary, but then you have only n values that point to something valid. You need to allocate the rest of the sub-arrays because the newly allocated memory points to unallocated/invalid areas. The error is not from accessing the pointer, but from dereferencing it.

You need to add something like:

for(int i = n; i < n+plus; i++) {
   twoDimArray[i] = malloc(m * sizeof(int));
}

(same goes for deallocation: first deallocate the arrays in a loop, then deallocate the array of pointers)

Aside:

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 1
    And also, `towDimArray = realloc(twoDimArray ... )` is a potential memory leak. – Iharob Al Asimi Nov 02 '17 at 16:08
  • yeah, if it returns `NULL`. – Jean-François Fabre Nov 02 '17 at 16:08
  • Thank you, that solves the issue! When deacllocating the new array, do i have to create a for-loop over the new size, i.e. for(int i = 0; i < n + plus; i++) { free(...) ...} ? – Alienbash Nov 02 '17 at 16:14
  • yes, you have to do that _before_ deallocating the array of pointers. – Jean-François Fabre Nov 02 '17 at 16:17
  • One follow up (if you think it is appropriate to create a new topic for it, let me know): If i want to reallocate memory in a way, that twoDimArray becomes smaller instead of larger by using "twoDimArray = (int**)realloc(twoDimArray, 5 * sizeof(int));", is my resulting twoDimArray, in which i can access "twoDimArray[0][j]" up to "twoDimArray[4][j]", j in {0, 1, 2, 3} ? Because when i do that, i can still access "twoDimArray[9][j]", even though i thought it is being freed by realloc()? – Alienbash Nov 02 '17 at 17:06