I have this method which reads a file but when I try to run it, it gives me an error for the return (char *) buffer.
Error: warning: function returns address of local variable [-Wreturn-local-addr]
char * readFile(char* filename, size_t chunk) {
FILE *proc;
size_t len = chunk;
char * buffer[len];
proc = fopen(filename, "r");
if(proc) {
if(buffer)
fread(buffer, 1, len, proc);
fclose(proc);
return (char *) buffer;
}return "error";
}
Should I be creating the buffer before the method outside the main for this method?
PS: I am aware this might be a duplicate question.
char*? That's interesting.char *buffer[len];and then you're returning achar *via cast? To avoid returning the local variable pointer, you can either (1) create the buffer before the function call and pass the buffer address to the function, or, (2) the function could dynamically allocate the buffer usingmallocand return that pointer as long as the caller handles freeing the memory when it's no longer needed. Option 2 is more prone to a memory leak.