从文件中使用 malloc 和 realloc 读取

Reading with malloc and realloc from file

我只想读取文件内容并将它们放入字符串中。
从文件读取时遇到问题。我开始使用 fgets 阅读,如果我的 space 不够用,我会重新分配内存。但是,当我尝试再次重新分配以收缩时,它崩溃了。我读到它可能与 malloc 的元数据有关,但我看不到我如何影响它们。提前致谢

 int readStringFromALE(int height,int width,char **stringImage,FILE *fout){
    char buffer[BUFFER_SIZE] = {'[=10=]'};
    *stringImage=(char *)malloc(sizeof(char)*BUFFER_SIZE+1);
    *stringImage[0]='[=10=]';
    int i=1;
    int size=sizeof(char)*BUFFER_SIZE,readSize=0;
    while(fgets(buffer, sizeof(buffer), fout) != NULL){
        strncat(*stringImage,buffer,strlen(buffer)+1);
        readSize+=strlen(buffer)+1;
        printf("%s",buffer);
        if(size<=readSize){
            char *temp;
            temp=(char *)realloc(*stringImage,i*BUFFER_SIZE*sizeof(char)+1);
            if(temp==NULL){
                printf("Unable to allocate memory\n");
                return EXIT_FAILURE;
            }
            i++;
            *stringImage=temp;
            size=i*BUFFER_SIZE*sizeof(char);
        }
        if (buffer[strlen(buffer) - 2] == ':')
            break;
    }
    char *temp=(char *)realloc(*stringImage,strlen(*stringImage)+10);
    if(temp==NULL){
        printf("Unable to allocate memory\n");
        return EXIT_FAILURE;
    }
    *stringImage=temp;
    return EXIT_SUCCESS;
}

尝试在每次调用时使用 fgets 读取到字符串的结尾 (*stringImage + len)。

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

#define BUFFER_SIZE 10

int readStringFromALE(int height,int width,char **stringImage,FILE *fout){
    char *temp = NULL;
    size_t size = 0;
    size_t dif = 0;
    size_t len = 0;

    while ( 1) {
        if ( NULL == ( temp = realloc ( *stringImage, size + BUFFER_SIZE))) {
            fprintf ( stderr, "problem realloc\n");
            free ( *stringImage);
            return 0;
        }
        *stringImage = temp;
        //len = strlen ( *stringImage);
        dif = BUFFER_SIZE + ( size - len);
        if ( fgets ( *stringImage + len, dif, fout)) {
            len += strlen ( *stringImage + len);
            if ((*stringImage)[strlen(*stringImage) - 2] == ':')
                break;
        }
        else {
            printf("\n\n---end of file---\n");
            break;
        }
        size += BUFFER_SIZE;
    }
    temp=(char *)realloc(*stringImage,strlen(*stringImage)+10);
    if(temp==NULL){
        printf("Unable to allocate memory\n");
        return EXIT_FAILURE;
    }
    *stringImage=temp;
    return EXIT_SUCCESS;
}

int main(int argc,char** argv){
    char *stringImage = NULL;//so realloc will act like malloc on first call
    int height = 0;
    int width = 0;
    FILE *fout = NULL;

    if ( NULL == ( fout = fopen ( "somefile.txt", "r"))) {
        perror ( "problem");
        return 0;
    }

    readStringFromALE( height, width, &stringImage, fout);
    fclose ( fout);
    printf("%s\n\n",stringImage);

    free ( stringImage);

    return 0;
}