c - 局部变量错误的返回地址

标签 c pointers

我输入了这段代码:

void main()
{
    int *a;
    a = foo();
    printf("%d\n", *a);
}

int* foo()
{
    int b = 10;
    return &b;
}

编译后出现2个问题:

1. error - Conflicting type for foo()
2. warning - function returns address of local variable

但是后来我写了这个

int* foo();
void main()
{
    int *a;
    a = foo();
    printf("%d\n", *a);
}

int* foo()
{
    int b = 10;
    return &b;
}

现在,编译后不报错了,这是显而易见的,但是,为什么编译器没有给出返回局部变量地址的警告呢?

声明或不声明函数如何影响局部变量的返回地址?

抱歉之前没有提到,但我正在使用 GNU GCC 编译器

最佳答案

C 标准不要求编译器给出除语法错误之外的警告。

ISO/IEC 9899:1999, 5.1.1.3:

A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint, even if the behavior is also explicitly specified as undefined or implementation-defined. Diagnostic messages need not be produced in other circumstances.

您描述的行为不一致(即不好)但有效/符合标准。

关于c - 局部变量错误的返回地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35262911/

相关文章:

c - 如何在文本文件中使用strtok

delphi - 在 Delphi XE 中将 UnicodeString 转换为 PAnsiChar

c++ - 如何处理带有指针的 map ?

c++ - 指针困惑

c - 如何有效地交错 8 个 __int16 数字中的位?

c - 反转数组,为什么除以2就可以了?

c - 在内核线程启动时使用 use_mm 和 set_fs

c - 为什么在while()中将printf()作为条件输出不同的输出

c++ - 我用 c 编写了一些代码来制作简单的 win32 窗口,但失败了

c++ - 对象的内部表示