Search code examples
cpointersmallocmemcpy

Modify buffer passed as a pointer


I'm trying to read into a buffer passed as a pointer to this function. memcpy() works fine and the data is stored correctly in buffer, but when I access buffer outside of the function it is null. There's some pointer issue I'm not getting here.

Here's the code, I took out most of it, I know it copies the data correctly, but it doesn't pass it to the buffer pointer. Ideas?

int read(file file, char *buffer , int maxlen) {
    int bytes_read;

    // copy data to file buffer
    bytes_read = min(maxlen, file->file_size - file->cursor);
    buffer = (char*) malloc(bytes_read);

    memcpy(buffer , file->buffer + file->cursor, bytes_read);

    return bytes_read;
}

Solution

  • The problem is pretty simple: you are modifying the variable "buffer". Since it is passed by value and not by reference, the calling function doesn't see the change. In order to make the change to buffer visible, you need to pass in a pointer to buffer.

    Your function would then look like this:

    int read(file file, char **buffer , int maxlen) {
        int bytes_read;
    
        // copy data to file buffer
        bytes_read = min(maxlen, file->file_size - file->cursor);
        *buffer = (char*) malloc(bytes_read);
    
        memcpy(*buffer , file->buffer + file->cursor, bytes_read);
    
        return bytes_read;
    }
    

    to call the function:

    rv = read(file, &buffer, maxlen);