在Visual Studio中编译此代码时没有错误。

huangapple go评论111阅读模式
英文:

No error compiling this code in visual studio

问题

#include<iostream>;

int* function() {
    int a = 2;
    return &amp;a;
}

int main() {
    int* b = function();
    *b = 3;
    return 0;
}
英文:
#include&lt;iostream&gt;

int* function() {
	int a = 2;
	return &amp;a;
}

int main() {
	int* b = function();
	*b = 3;
	return 0;
}

I was trying to run this program, but this is supposed to give me an error because a should be deleted after leaving the function. However, I received no error in Visual Studio 2022. a is not even a static variable, nor is b constant.

I tried to copy and paste this code in different compilers to see if the lecture was wrong, but I recieved

> main.cpp:4:16: warning: address of local variable ‘a’ returned [-Wreturn-local-addr]

like what it is supposed to be.

答案1

得分: 1

你应该会收到警告:C4172:在Visual Studio中返回局部变量或临时变量的地址。

而MSVC文档编译器警告(级别1)C4172将其视为编译器警告。
所以默认情况下不会报错。

英文:

You should receive warning: C4172: returning address of local variable or temporary: a, in Visual Studio.

And MSVC doc Compiler Warning (level 1) C4172 treats it as a Compiler Warning.
So you don't get an error by default.

huangapple
  • 本文由 发表于 2023年8月10日 09:36:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76872136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定