0

I was trying to practice malloc'ing and freeing memory, however when I run the free() function in this program an error is returned for an invalid pointer. Can anyone tell me what I'm doing wrong?

Here's the error:

Error in `./malloc1': free(): invalid pointer: 0x000000000216c421
Aborted

And here's my code:

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

int main (void)
{
    //open an old file
    FILE* old_file = fopen("words.txt", "r");
    if (old_file == NULL)
    {
        printf("No file found.");
        return 1;
    }
    
    //open a new file
    FILE* new_file = fopen("new_words.txt", "w");
    if (new_file == NULL)
    {
        printf("Unable to create file.");
        return 2;
    }
    
    for (int i = 0; i < 21; i++)
    {
        char* storage = malloc(sizeof(char));
        if (storage == NULL)
        {
            printf("Error.");
            return 3;
        }
        fread(&storage, sizeof(char), 1, old_file);
        fwrite(&storage, sizeof(char), 1, new_file);
        free(storage);
    }

    //close both files
    
    fclose(old_file);
    fclose(new_file);
}

1 Answer 1

4

The problem lies in fread(&storage, sizeof(char), 1, old_file); This line is storing the data read directly in the pointer, overwriting the address of the malloc'd memory. It isn't storing the data at the memory pointed to by the address stored in the pointer. When the free() call is executed, it's trying to free an invalid address. It is also creating a memory leak because the address of the malloc'd memory is being replaced. Remove the & from the fread() and fwrite() and it will work.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .