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

Mic*_*alf 1 c malloc realloc

#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 
Run Code Online (Sandbox Code Playgroud)

以上代码就是我所拥有的.它一直给我一个错误,我似乎无法搞清楚.使用valgrind,它表示大小为4的写入无效.有任何建议或见解吗?

pax*_*blo 6

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

看看你的两个分配线:

line_array = malloc(10 * sizeof(int));
line_array = realloc(line_array, realloc_counter);
Run Code Online (Sandbox Code Playgroud)

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

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

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

应该做的是:

line_array = realloc(line_array, realloc_counter * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你应该可以检查来自返回值malloc,并realloc看看他们是否失败.假设他们总能工作并不是一个好主意.