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.