简体   繁体   English

C语言。 功能异常

[英]C language. Strange function behavior

So i am writing a program which generates functions. 所以我正在编写一个生成函数的程序。 I am simulating lambda expressions with GCC nested functions. 我正在用GCC嵌套函数模拟lambda表达式。 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. 该程序应该只打印N次'1337',但是该程序只打印一次并且发疯。

#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: 正如GCC的嵌套函数文档中所述:

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. 换句话说,您在此处尝试做的事情-返回对嵌套函数的引用-并未真正受到GCC的认可。 To whatever extent it works correctly, you're just getting lucky, because GCC doesn't mean to support this functionality. 无论它在何种程度上正常运行,您都非常幸运,因为GCC并不意味着支持此功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM