-1

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.

Anonymous
  • 57
  • 1
  • 9
  • 4
    So you wanted an array of `char*`? That's interesting. – Bathsheba Mar 01 '16 at 13:52
  • Not clear why you have `char *buffer[len];` and then you're returning a `char *` 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 using `malloc` and 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. – lurker Mar 01 '16 at 13:53
  • @Bathsheba yes, as in a string char array. – Anonymous Mar 01 '16 at 13:53
  • Let caller allocate the space, callee fill the data in – user3528438 Mar 01 '16 at 13:54
  • @lurker thank you. I'll give that a try :) – Anonymous Mar 01 '16 at 13:54
  • 4
    That you need to cast that return value should be a clear indicator that you do something wrong. – Some programmer dude Mar 01 '16 at 13:55

1 Answers1

1

To begin with, judging from return "error", you want buffer to be an array of characters, not an array of pointers to characters. Fix this first.

As for the local variable issue, simply modify the function into this:

void readFile (const char* filename, size_t chunk, char buffer[chunk])

This forces the caller to deal with the allocation and your function only needs to focus on its designated task.

Lundin
  • 195,001
  • 40
  • 254
  • 396