重新分配给出错误-下一个大小无效 [英] realloc is giving error - invalid next size
问题描述
#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
上面的代码就是我所拥有的.它一直给我一个错误,我似乎无法弄清楚.使用valgrind表示大小为4的写入无效.有什么建议或见解吗?
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?
推荐答案
使用动态内存分配时,错误消息的无效的下一个大小"样式通常是因为您通过超出分配的缓冲区末尾写入而破坏了内存区域
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.
看看您的两条分配线:
line_array = malloc(10 * sizeof(int));
line_array = realloc(line_array, realloc_counter);
第一个方法是将元素计数乘以元素大小,以便分配的 bytes 数目正确.第二个是仅使用元素 count 而不将其乘以元素大小.
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.
因此,第一次进行重新分配时,realloc_counter
设置为20,因此几乎可以肯定缩小分配的内存(尽管这取决于整数的相对大小)和字节,当然).
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).
例如,如果sizeof(int) == 4
,则首先分配正确的40个字节,然后在需要为80时重新分配20个字节.
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));
顺便说一句,您还应该检查malloc
和realloc
的返回值以查看它们是否失败.假设它们将一直有效并不是一个好主意.
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.
这篇关于重新分配给出错误-下一个大小无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!