realloc is giving error - invalid next size

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

#include <stdlib.h> #include <stdio.h> #include <string.h>  int temp;   int main() {     FILE * fp;     fp = fopen("input2.txt", "r");                      //Open the input     int counter = 0;      int realloc_counter = 10;       int *line_array;                                    //Initialize the array     line_array = malloc(10 * sizeof(int));              //Allocate memory for initial ten numbers, of size int for each       while (fscanf(fp, "%d", &temp) > 0)     {         line_array[counter] = temp;          counter ++;          if (counter % 10 == 0)         {                    realloc_counter = realloc_counter * 2;             line_array = realloc(line_array, realloc_counter);         }       }        fclose(fp);                                         //Close the input file     free(line_array);                                   //Free the memory 

The above code is what I have. It keeps giving me an error and I can't seem to figure it out. Using valgrind it says there is an invalid write of size 4. Any suggestions or insight?

回答1:

The "invalid next size" style of error message when using dynamic memory allocation is usually because you have corrupted the memory arena by writing beyond the end of an allocated buffer.

Have a look at your two allocation lines:

line_array = malloc(10 * sizeof(int)); line_array = realloc(line_array, realloc_counter);

The first is multiplying the element count by the element size so that the number of bytes allocated is correct. The second is just using the element count on its own without multiplying it by the element size.

So the first time you do a re-allocation, realloc_counter is set to 20, so you'll almost certainly shrink the memory allocated (though this depends on the relative sizes of your integers and bytes, of course).

For example, if sizeof(int) == 4, you first allocate the correct forty bytes, then reallocate twenty, when what you need is eighty.

What you should be doing is something like:

line_array = realloc(line_array, realloc_counter * sizeof(int));

As an aside, you should also be checking the return values from both malloc and realloc to see if they fail. It's not really a good idea to assume they'll always work.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!