realloc 无法正确复制值

Ily*_*lya 3 c

我正在尝试将大小未知的文本文件读入数组中。我通过一次将一个字符读入数组并在到达数组末尾时重新分配内存来实现这一点。

从数组大小从 16 增加到 32 开始,realloc 方法仅复制前 4 个字符。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main()
{
    int *text_arr = malloc(1*sizeof(int));
    text_arr[0] = '\0';
    int text_len=1;
    int i=0;
    FILE *fp;

    fp = fopen("1.txt", "r");
    
    while ((text_arr[i] = fgetc(fp)) != EOF) {
        /* increment i for next loop */
        i++;

        /* extend the array if needed */
        if (i >= text_len) {
            /* debug prints */
            printf("Text: ");
            for (int n=0; n<i; n++)
                printf("%c,", text_arr[n]);
            printf("\n\n");
            
            /* double array size */
            text_len *= 2;
            text_arr = (int*)realloc(text_arr, text_len);
        }
    }
    text_arr[i] = '\0';

    fclose(fp);
    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

可能是什么问题呢?

Oka*_*Oka 7

您正在使用sizeof (int)大小的对象,需要确保在重新分配时将请求的字节数乘以该大小。

realloc(text_arr, sizeof (int) * text_len);
Run Code Online (Sandbox Code Playgroud)