Search code examples
cdynamic-memory-allocationc-strings

Allocate memory in a function, then use it outside


I want to allocate memory inside a function with malloc and then return the buffer. Then I want to be able to strcpy a string into that buffer from outside of the function.

Here is my current code

#include <stdlib.h>
#include <string.h>

char allocate_mem(void) {
    char *buff = malloc(124); // no cast is required; its C

    return buff // return *buff ?
}

int main(int argc, char const *argv[])
{
    char buff = allocate_mem();
    strcpy(buff, "Hello World");
    free(buff);
    return 0;
}
// gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0

Solution

  • The variable buff within the function has the type char *. So if you want to return the pointer then the function has to have the return type char *.

    char * allocate_mem(void) {
        char *buff = malloc(124); // no cast is required; its C
    
        return buff // return *buff ?
    }
    

    And in main you have to write

    char *buff = allocate_mem();
    

    Pay attention to that it is not a good idea to use the magic number 124 in the function.

    A more meaningful function could look the following way

    char * allocate_mem( const char *s ) {
        char *buff = malloc( strlen( s ) + 1 ); // no cast is required; its C
        
        if ( buff ) strcpy( buff, s );
    
        return buff // return *buff ?
    }
    

    And in main you could write

    char *buff = allocate_mem( "Hello World" );
    //...
    free(buff);
    

    Another approach is to use as a parameter an integer value that will specify the size of the allocated memory. For example

    char * allocate_mem( size_t n ) {
        char *buff = malloc( n ); // no cast is required; its C
    
        return buff // return *buff ?
    }