Realloc fails after the 10th iteration inside a loop

后端 未结 2 340
感动是毒
感动是毒 2021-01-27 06:29

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

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-27 06:54

    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;
    

提交回复
热议问题