Search code examples
cmemorymemory-managementdynamic-memory-allocationfree

How does free() works in this case?


Let's say a function allocates memory for a string and returns it. The variable, that calls that function, in which is stored its return string is an array of pointers to char already dynamically allocated. My doubt is, when I'll free the variable's memory, is it going to free both the variable memory and the in-function string memory or does the in-function allocated memory became one with the variable one?

char *function() {
    //allocates memory for <string>
    return <string>
}

int main() {
    //<variable> declaration
    //<variable> allocation
    <variable> = function();
    free(<variable>);
    return 0;
}
   

For practical reasons I omitted the //function declaration part

Thanks for your attention and help!


Solution

  • There are two possible cases:

    1. Function allocates memory using dynamic memory allocation and it is 100% correct
    char *func(void)
    {
        char *x = malloc(100);
        /* some code */
        return x;
    }
    
    void foo(void)
    {
        char *y = func();
        free(y);
    }
    
    
    1. Other ways of allocating memory. All invoke the undefined behavior when you try to free them. Additionally there is an another UB when pointer to automatic variable is used outside the scope it was defined in.
    char w[100];
    
    char *func(void)
    {
        char x[100];
        /* some code */
        return x;
    }
    
    char *func1(void)
    {
        static char x[100];
        /* some code */
        return x;
    }
    
    char *func2(void)
    {
        return w;
    }
    
    
    void foo(void)
    {
        char *y = func();
        y[0] = 'a';       //UB
        free(y);          //UB
    
        y = func1();
        y[0] = 'a';
        free(y);        //UB
    
        y = func2();
        y[0] = 'a';
        free(y);        //UB
    }