문제

So i am writing a program which generates functions. I am simulating lambda expressions with GCC nested functions. But I came across with strange program actions. Maybe i do not know some theory behind this, witch leads my program to do strange actions. Here I wrote very simplified code, I pointed down below where is the problem. The program should just print N times '1337', but the program just prints it once and goes crazy.

#include <stdio.h>
#include <stdlib.h>

#define lambda(return_type, function_body) \
    ({ \
        return_type __fn__ function_body \
        __fn__; \
    })

void init(void (**fn)()){
    int num = 1337;
    *fn = lambda(void,(){printf("%d\n",num);});
}

int main(){
    void (*fn)();
    init(&fn);
    fn(); // Everything is fine, it prints '1337'
    fn(); // It prints '-1869573949' , maybe accessing memory somewhere
    fn(); // It does not print anything at all
    ...   // It does not print anything at all
    return 0;
}

I want to point out that if I change

void init(void (**fn)()){
    int num = 1337;
    *fn = lambda(void,(){printf("%d\n",num);});
}

to

void init(void (**fn)()){
    *fn = lambda(void,(){printf("%d\n",1337);});
}

It works, but it does not satisfy my needs.

I appreciate any help or information given about this problem, because I am really interested in it.

도움이 되었습니까?

해결책

As noted in the documentation for GCC's nested functions:

If you try to call the nested function through its address after the containing function exits, all hell breaks loose. If you try to call it after a containing scope level exits, and if it refers to some of the variables that are no longer in scope, you may be lucky, but it's not wise to take the risk.

In other words, what you're trying to do here — returning a reference to a nested function — is not really sanctioned by GCC. To whatever extent it works correctly, you're just getting lucky, because GCC doesn't mean to support this functionality.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top