是我的代码未定义的行为 [英] Is my code undefined behavior

查看:132
本文介绍了是我的代码未定义的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的函数有未定义的行为吗? 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆