Realloc fails after the 10th iteration inside a loop

后端 未结 2 338
感动是毒
感动是毒 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;
    
    0 讨论(0)
  • 2021-01-27 07:04

    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)

    0 讨论(0)
提交回复
热议问题