1

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;
}
J doe
  • 13
  • 4
  • There is [no need](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc#605858) to cast the result of a call to `malloc()`. – ad absurdum Oct 29 '16 at 00:23
  • 3
    You've written `n++` inside your loop. This means `n` will increase by 2 with every loop iteration. Is this a mistake? – byxor Oct 29 '16 at 00:23
  • It's fine to realloc each time – M.M Oct 29 '16 at 00:24
  • 1
    @BrandonIbbotson it certainly is a mistake, as the first `realloc` allocates `2` rows, and then `stringlist[2] = ` writes out of bounds – M.M Oct 29 '16 at 00:27
  • The normal structure of code like this is to do the `realloc()` **before** you put something into the new element. – Barmar Oct 29 '16 at 00:33

1 Answers1

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • thanks, i read the code like 10 times but didn't notice the n++, i guess i need some sleep – J doe Oct 29 '16 at 02:08
  • How did you miss it when you stepped through the program in the debugger, though? You did try using a debugger before posting here, didn't you? – Barmar Oct 29 '16 at 22:32