Search code examples
cfreadcoredump

Coredump in fread when pointing to file in array


Recently started working with pointers and have created a little script that is supposed to stich together some textfiles.

However when i try to call fputs i get a coredump/segmentation error. I suspect it is because of the way that the file pointer is saved. I find the files saves it in an array and tries to retrieve it later on.

the FILE pointer is saved in a struct. Does somebody instantly spot my fault? i would be very grateful!

The struct:

typedef struct{
int listSize;
int listCapacity;
FILE *fileStream;
}FileList;

Creating the struct

FileList fileList;
fileList.listSize=0;
fileList.listCapacity=1;
fileList.fileStream=calloc(fileList.listCapacity,sizeof(FILE));

and then i add the struct to the array by calling

void addFile(FileList* list, FILE* file)
{
    list->fileStream[list->listSize]=*file;
}

However when i call

char* buffer[10];
size_t result=0;

result = fread(buffer,1,10,&fileList.fileStream[ii+currentGroupOffset]);
    fputs(*buffer,outPutFile);

it crashes, i tried to watch the value ii+currentGroupOffset making sure it doesnt go out the array bounds

any help at all appriciated! :)


Solution

  • You can't allocate and copy around FILE structures yourself - it's an opaque data type. So, instead of creating an array of FILE structures, create an array of FILE * pointers:

    typedef struct {
        int listSize;
        int listCapacity;
        FILE **fileStream;
    } FileList;
    
    FileList fileList;
    
    fileList.listSize = 0;
    fileList.listCapacity = 1;
    fileList.fileStream = calloc(fileList.listCapacity, sizeof fileList.fileStream[0]);
    

    then add a FILE * pointer to the array by copying the pointer value:

    void addFile(FileList *list, FILE *file)
    {
        list->fileStream[list->listSize] = file;
    }
    

    and use it like so:

    char buffer[10];
    size_t result = 0;
    
    result = fread(buffer, 1, 10, fileList.fileStream[ii+currentGroupOffset]);
    fwrite(buffer, 1, result, outPutFile);