gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:47 24 4
gpt4 key购买 nike

我输入了这段代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com