I\'m trying to get a sequence of letters from the user, and put the input inside a dynamic array.
However, from a reason I can\'t quite figure out - realloc fails (retu
of course it fails:
memory_check = realloc(first_string, (i+1)*(sizeof(char)));
if(memory_check == NULL) {
printf("\nError allocating memory!\n");
break;
}
you're using memory_check
as a flag to check if you can reallocate, but it's not only that.
You have to assign it back to first_string
.
In your case, it's a dead giveaway: the first 10 times (in your case, of course, this isn't specified or defined, it's pure random), the memory region doesn't need to be moved, which explain that it works. But after a while, realloc
cannot reuse the same block (because it's too small) and it changes the memory location.
Since you're not updating it, you get undefined behaviour.
You could do this:
memory_check = realloc(first_string, (i+1)*(sizeof(char)));
if(memory_check == NULL) {
printf("\nError allocating memory!\n");
free(first_string);
break;
}
first_string = memory_check;
You are writing to deallocated memory.
memory_check
is the newly reallocated pointer, you need to trade this value with first_string
. first_string points to memory that has already now been freed (by realloc)