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);
}