是我的代码未定义的行为 [英] Is my code undefined behavior
问题描述
我的函数有未定义的行为吗? Becouse有局部变量c,所以它在自动位置,因此它会在执行函数后被销毁? (范围结束)
int * calculate(int * a,int * b)
{
int c =(* a)+(* b); // local variable c
return& c;
}
int main()
{
int a = 12;
int b = 23;
int * ptr = calculate(& a,& b);
std :: cout<< * ptr<< endl;
}
因为在退出函数计算$ c $后,会产生一个临时局部对象和取消引用,即未定义的行为
* ptr
)。 您可以使用正常变量,删除那些 *
:
int calculate (int * a,int * b)
{
int c =(* a)+(* b);
return c;
}
因为你没有什么合理的通过指针, *
:
int calculate(int a,int b)
{
int c = a + b;
return c;
}
Is my function has undefined behavior? Becouse there is local variable c, so its in automatic location so it will be destruct after execution of function? (end of scope)
int* calculate(int* a,int* b)
{
int c=(*a)+(*b); //local variable c
return &c;
}
int main()
{
int a=12;
int b=23;
int* ptr=calculate(&a,&b);
std::cout<<*ptr<<endl;
}
Yes, returning a pointer to a temporary local object and dereferencing that is undefined behavior.
Because after exiting the function calculate
, that object goes out of scope and automatically will be destroyed, then the provided pointer, points to an invalid address and it's a dangling pointer. After that, you can use dereference and use it (for example: *ptr
).
In your case, you can use a normal variable, remove those *
:
int calculate(int *a, int *b)
{
int c = (*a)+(*b);
return c;
}
since you have nothing reasonable to pass them by pointer, it's better to remove more *
:
int calculate(int a, int b)
{
int c = a + b;
return c;
}
这篇关于是我的代码未定义的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!