Question

I used fwrite() function to write 4 blocks of data into a file called "example2.bin". At the very beginning of the file, I also write the number of blocks (4 in this chase). Each block contains data in the following format: 0 (offset), 4 (size of the string), and the string "dang".

I first copied the memory address to char *buffer, which contains the number of blocks, and the 4 blocks of data as explained above. I then did the following:

filePtr = fopen("example2.bin", "wb+");
fwrite(buffer, contentSize, 1, filePtr); /*contentSize is the sum of the 4 blocks in byte */

The fwrite() worked well, and I was able to see the string saved in the file example2.bin. However, I have problem parsing the file example2.bin:

int main()
{

    FILE *filePtr;
    int listLength = 0;
    int num_elements = 0;
    int position = 0;
    int offset = 0;
    int size = 0;
    char *data;

    listLength = fileSize("example2.bin");  /* get the file size in byte */
    filePtr = fopen("example2.bin", "rb");

    fread(&num_elements, 1, 1, filePtr);   /* get the number of blocks saved in this file */
    printf("num_elements value is %d \n", num_elements);
    position += sizeof(num_elements);     /* track the position where the fread() is at */
    printf("before the for-loop, position is %d \n", position);

    int index;
    for (index = 0; index < num_elements; index++)
    {
        fread(&offset, position, 1, filePtr);
        position += sizeof(offset);
        printf("offset is %d and position is %d \n", offset, position);

        fread(&size, position, 1, filePtr);
        position += sizeof(size);
        printf("size is %d and position is %d \n", size, position);

        fread(data, position, 1, filePtr);
        position += size;
        printf("size is %d and data is %s \n", size, data);
    }
    return 0;
}

When I run the compiled program, I got the following outputs, which is weird to me:

num_elements value is 4
before the for-loop, position is 4
offset is 0 and position is 8
size is 67108864 and position is 1996488708 Segmentation fault (core dumped)

I do not understand why the size and the position increased to such big numbers. I appreciate your help.

Was it helpful?

Solution

I think I've found out the reason for the segmentation fault error: I did not allocate memory for the pointer data

the segmentation fault error is gone after doing a malloc: data = malloc(size); before this line fread(data, size, 1, filePtr);

at the end of the for-loop, I also need to free up the allocated memory by: free(data);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top