0

I was wondering why realloc for a char* or whatever 1D array works if I do something like oldpointer=realloc(oldpointer,newsize);

But when I try with a 2D char* array it fails. Looking here and there I see that sometimes people use NewPointer=realloc(oldpointer,newsize) but if it's the only use it will not be useful to me, since I need to resize the matrix' columns and rows often, in a loop (I must fill an array of strings without knowing first how many string I will insert nor the size of each one)

the code I used for trying is this,

void main(){
    int max = 5, i,j;
    char **matrix;
    matrix=malloc(max*sizeof(char));
    for(i=0;i<max;i++){
        matrix[i]=malloc(max*sizeof(char));

    }
    matrix=realloc(matrix,max*2*sizeof(char));

    strcpy(matrix[4],"we\0");
    printf("%s",matrix[4]);

}

Error in `./out': realloc(): invalid next size: 0x00000000015c4010 *** Aborted

ro.nin
  • 121
  • 5
  • 13
  • 2
    This is a bad `realloc()` -> `matrix=realloc(matrix,max*2*sizeof(char)); ` in case of failure you can't do anything to recover. Also, `"we\0"` is absolutely unnecessary, `"we"` is enough. Ans `sizeof(char) == 1` by definition. – Iharob Al Asimi Mar 17 '15 at 15:35
  • 2
    To my understanding, the first `malloc` does not work as expected. Shouldn't it be `matrix = malloc(max*sizeof(char*))`? – Codor Mar 17 '15 at 15:37
  • @Codor yes, you are right. – Iharob Al Asimi Mar 17 '15 at 15:38

2 Answers2

0

The problem is that your double pointer can't hold pointers because you did not allocate enough space.

matrix = malloc(max * sizeof(char));
/* which is exactly the same as
 * matrix = malloc(max);
 */

should be

matrix = malloc(max * sizeof(char *));
/*                        ^ max pointers, so sizeof a poitner */ 

then if you want to realloc(), you can do it like this

void *pointer;

pointer = realloc(matrix, 2 * max * sizeof(char *));
if (poitner == NULL)
    handleFailure_OrExit_ButDoNot_Use_The_Realloced_Poitner();
matrix = pointer;

Always check the return value of a function if it returns one, for example malloc()/calloc()/realloc() "and any custom implementation normally", return NULL on failure.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

First your matrix is an array of char*, so you should be allocating:

matrix=malloc(max * sizeof(char*));

Likewise for the realloc().

You also don't need "we\0", "we" would suffice. All strings in double quotes are NUL terminating string literals. Allocate enough memory for each of char*s and the chars and you should be good.

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34