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;
}
5
  • There is no need to cast the result of a call to malloc(). Commented Oct 29, 2016 at 0:23
  • 3
    You've written n++ inside your loop. This means n will increase by 2 with every loop iteration. Is this a mistake? Commented Oct 29, 2016 at 0:23
  • It's fine to realloc each time Commented Oct 29, 2016 at 0:24
  • 1
    @BrandonIbbotson it certainly is a mistake, as the first realloc allocates 2 rows, and then stringlist[2] = writes out of bounds Commented Oct 29, 2016 at 0:27
  • The normal structure of code like this is to do the realloc() before you put something into the new element. Commented Oct 29, 2016 at 0:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, i read the code like 10 times but didn't notice the n++, i guess i need some sleep
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.