J doe J doe - 1 month ago 11
C Question

Dynamic allocation of 2D char array in C

i know its a bad idea to use realloc each time you add an item but im just trying to learn about memory management here.Why is this program crashing ?

#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "some text";
char **stringList = (char**) malloc( sizeof(char*));

for (int n=0;n<15;n++){
stringList[n] = (char*) malloc( (strlen(str)+1) );
strcpy(stringList[n], str);
stringList=realloc(stringList, (n+2) * sizeof(char*));
n++;
}

return 0;
}

Answer

The reason it's crashing is because you're incrementing n twice. You have n++ in the for() header, and then again at the bottom of the loop.

The first time through the loop everything works fine. Your initial allocation of the array has 1 element, you've set n = 0, so assigning to stringList[n] is fine.

Then you do realloc(stringList, (n+2)*sizeof(char*)). Now the array has 2 elements.

n++ at the bottom of the loop sets n = 1, and n++ in the for() header sets n = 2.

Then you go back into the loop body, and try to assign to stringList[n]. This is outside the array bounds, because n = 2 and the only valid indexes are stringList[0] and stringList[1].

This repeats every further time through the loop, always assigning to the array element just past the end. Accessing outside the bounds of an array causes undefined behavior, and you're getting a crash as a result.

Get rid of the n++ at the bottom of the loop and you should be OK.

Comments