I have to write a program that is able to take in a file of grades, read them, and then provide some options to be able to edit that file. I decided to write it in C (for the challenge, and to learn more about C). I have a function that receives a pointer, and then opens a file and loads the characters from that file, into the memory provided by that pointer.
The issue I am having is while using realloc to get a list size big enough to load the file in. I'm currently just loading in a filler size.
For reference: Function to load in data from file to list.
void loadFile(char **fileContents) {
printf("%p\n", *fileContents);
*fileContents = realloc(*fileContents, 200);
printf("%p\n", *fileContents);
printf("%zu\n", sizeof *fileContents);
}
Function to select various options to edit that list (also where fileContents
is declared).
void menu() {
char *fileContents = malloc(sizeof(char) * 20);
if (fileContents == NULL) {
puts("memory failed to initialize");
}
loadFile(&fileContents);
printf("%s\n", fileContents);
free(fileContents);
}
I was expecting to get a size of 200 for the last print statement in the loadFile
function, but instead I got 4.
In your loadFile
function, fileContents
is a pointer. Evidently on your system, pointers are 32-bits or 4 bytes.
The pointer you get back from malloc
, calloc
, realloc
doesn't carry any information about how much data was allocated. It's just a pointer to the beginning of that memory block.
As a further note, there is no guarantee these functions succeed. You should test to ensure they do. If they fail you can either print an error and exit or try to recover.
However, in order to do this with realloc
you want to first assign the result to a temporary variable. If it failed in your case, the memory pointed to by *fileContents
would no longer have a pointer pointing to it. This can cause a memory leak, since we could no longer free
it.