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?