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

标签 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 

上面的代码是我的。它一直给我一个错误,我似乎无法弄清楚。使用 valgrind 它说有一个大小为 4 的无效写入。有什么建议或见解吗?

最佳答案

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

看看你的两条分配线:

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

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

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

例如,如果 sizeof(int) == 4,您首先分配正确的 40 个字节,然后在您需要的是 80 个时重新分配 20 个。 p>

应该做的是:

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

顺便说一句,您应该检查mallocrealloc 的返回值,看它们是否失败。假设它们总是有效并不是一个好主意。

关于c - realloc 给出错误 - 下一个大小无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32962390/

相关文章:

android - 当传递给 JNI 层下的 C 函数时,指针的地址发生变化

c - 未打印指针字符串的第一个字符

c - c.. 中的 realloc() 打印垃圾值

c - 重新分配一个包含指向另一个结构的指针的结构(段错误)

c - 如何在 C 中打印数组元素的摘要

c - 重新分配字符串数组

c - 从 C 中的函数返回数组 : Segmentation Fault

c - 返回 1.0f 给我 1065353216

c - 带公式的结构

c - 链接列表问题 - 当用户输入 'N 停止添加更多元素时,为什么会添加 0 作为元素到我的列表中?