Ajith C Narayanan
Ajith C Narayanan

Reputation: 616

Where the nested function's body kept?

Please check the following code,

#include <stdio.h>
#include <string.h>

void* make_adder_function(int a)
{

    char str[64] ={};

    sprintf(str,"this function adds %d with input",a);

    void adder(int b) {
        int x = a;
        char ptr[64] = {};
        strcpy(ptr,str);
        printf("%s\n", ptr);
        printf("%d + %d = %d\n", x, b, x+b);
    }

    return adder;
}


int main()
{
    void (*adder_ten)(int);
    void (*adder_twenty)(int);

    adder_ten = make_adder_function(10);
    adder_twenty = make_adder_function(20);

    adder_ten(20);
    adder_twenty(20);

    return 0;
}

While Running the code I am getting the following output,

ajith@chat:~/Desktop$ ./a.out 
this function adds 20 with input
20 + 20 = 40
Segmentation fault (core dumped)

It shows like the scope of function adder() is only inside the make_adder_function(), I assumes this happens because the function body of adder() is kept in the stack frame of make_adder_function(). Can anybody give an explanation for this? How can I persist a nested function's lifetime throughout the program?

Upvotes: 0

Views: 76

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

Your problem (the non-standard extension aside) is that the local variable str inside the make_adder_function function will have ended its life-time when the make_adder_function function ends. And this happens before you call the adder function, which then tries to use the non-existing str variable.

The nested-function extension only nests functions, it doesn't have closures.

As a simple workaround you could make str a static variable. Its life-time would then be for the full runtime of the program. The problem then is that there's only one variable, which will be shared between all calls to the make_adder_function function.

Upvotes: 1

Related Questions