Task

Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index    i     (you may choose to start     i     from either    0    or    1),    when run, should return the square of the index,   that is,     i  2.

Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.



Goal

Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.

In imperative languages, one would generally use a loop with a mutable counter variable.

For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.

See also: Multiple distinct objects

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/mman.h>
 
typedef int (*f_int)();
 
#define TAG 0xdeadbeef
int _tmpl() { 
	volatile int x = TAG;
	return x * x;
}
 
#define PROT (PROT_EXEC | PROT_WRITE)
#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) 
f_int dupf(int v)
{
	size_t len = (void*)dupf - (void*)_tmpl;
	f_int ret = mmap(NULL, len, PROT, FLAGS, 0, 0);
	char *p;
	if(ret == MAP_FAILED) {
		perror("mmap");
		exit(-1);
	}
	memcpy(ret, _tmpl, len);
	for (p = (char*)ret; p < (char*)ret + len - sizeof(int); p++)
		if (*(int *)p == TAG) *(int *)p = v;
	return ret;
}
 
int main()
{
	f_int funcs[10];
	int i;
	for (i = 0; i < 10; i++) funcs[i] = dupf(i);
 
	for (i = 0; i < 9; i++)
		printf("func[%d]: %d\n", i, funcs[i]());
 
	return 0;
}