Basically the problem comes down to this:
I load a file, write all the each character into a char* variable which has malloc() the length of the file. Then I return that variable and print it, then I free() the memory for that variable and try to print the variable again which does print it.
I'm very new to C so there is probably something wrong in the way I handle the memory for the variable that holds the text content.
I tried using char[(ftell(file)] instead of malloc and char*, but then the function didn't return anything. That's probably because it's a local variable which gets freed when the function does return, right?
Here's what my code looks like:
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "data/filesystem/files.h"
int main(){
char *filebuffer = retrieve_file_content("assets/test.txt");
printf("%s", filebuffer);
free(filebuffer);
printf("%s", filebuffer);
return 0;
}
files.c:
#include <stdio.h>
#include <stdlib.h>
char *retrieve_file_content(char* path){
FILE *file;
file = fopen(path, "r");
if(file){
fseek(file, 0L, SEEK_END);
char *filebuffer = malloc(ftell(file));
if(filebuffer == NULL){ return NULL; }
fseek(file, 0L, SEEK_SET);
int i = 0;
int buffer = getc(file);
while(buffer != EOF){
filebuffer[i] = buffer;
buffer = getc(file);
i++;
}
fclose(file);
return filebuffer;
}else{
return NULL;
}
}
test.txt:
heheasdasdas
output:
heheasdasdas
heheasdasdas
Thanks in advance!
free just marks that the memory in question is free to be allocated again, that means it can be reused. But it doesn't set the freed memory to any value. Your example is what is called UB (Undefined Behavior). Programs having Undefined Behavior may technically do anything - including wrong/strange behavior, good behavior, or ordering a pizza via skype :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With