-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.

6
  • 4
    So you wanted an array of char*? That's interesting. Commented Mar 1, 2016 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. Commented Mar 1, 2016 at 13:53
  • @Bathsheba yes, as in a string char array. Commented Mar 1, 2016 at 13:53
  • Let caller allocate the space, callee fill the data in Commented Mar 1, 2016 at 13:54
  • 4
    That you need to cast that return value should be a clear indicator that you do something wrong. Commented Mar 1, 2016 at 13:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.