realloc给出错误 – 下一个大小无效

#include  #include  #include  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 

以上代码就是我所拥有的。 它一直给我一个错误,我似乎无法弄明白。 使用valgrind,它说大小为4的写入无效。有任何建议或见解吗?

使用动态内存分配时,“无效的下一个大小”样式的错误消息通常是因为您通过写入超出已分配缓冲区的末尾来破坏内存区域。

看看你的两个分配线:

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

第一种是将元素数乘以元素大小,以便分配的字节数是正确的。 第二种方法是单独使用元素计数而不将其乘以元素大小。

因此,第一次进行重新分配时, realloc_counter设置为20,因此您几乎肯定会缩减分配的内存(当然,这取决于整数和字节的相对大小)。

例如,如果sizeof(int) == 4 ,则首先分配正确的四十个字节,然后重新分配二十个,当你需要的是八十个。

应该做的是:

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

另外,您应该检查mallocrealloc的返回值,看它们是否失败。 假设他们总能工作并不是一个好主意。