英文:
No error compiling this code in visual studio
问题
#include<iostream>;
int* function() {
int a = 2;
return &a;
}
int main() {
int* b = function();
*b = 3;
return 0;
}
英文:
#include<iostream>
int* function() {
int a = 2;
return &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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论