gcc 6.1.0分段错误 - gcc bug? [英] gcc 6.1.0 segmentation fault - gcc bug?

查看:171
本文介绍了gcc 6.1.0分段错误 - gcc bug?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一下代码。事实上,这是狭义的问题,我发现使用gmock和模拟无效(void)方法。

  class Base {
public :
virtual〜Base(){}
};

类派生:public base
{
public:
void GetValueAndDelete(){delete this; } //这里我们碰到
};

int main(){
Derived * p = 0;
p-> GetValueAndDelete();
}

建立它:

  /tools/gcc6.1/bin/g++ --version 
g ++(GCC)6.1.0

优化级别与-O0不同,运行结果会导致分段错误。

是gcc bug还是一些与c + +代码(是的,是的,我知道它使用副作用,但它与其他编译器一起工作,并没有优化,以及)

解决方案


是gcc错误吗?

否。


或用c ++代码的东西


是的。对不指向有效对象的指针使用箭头运算符。这有未定义的行为。


以这种方式取消引用空指针和调用方法不会使用任何成员。 根据标准,这不是很好。它是UB。
$ b


什么是指针调用方法?


具体实现。


删除这个没什么特别的。

删除这个是非常特殊的。



是的,您应该只注意不要使用任何会员。是的,您必须确保只使用 new 创建函数被调用的所有实例。没有自动对象,没有静态对象没有 new [] ,no malloc +展示位置new。



所以是的,你可以 删除这个,但要小心。


Let's consider follwing code. In fact this is narrowed problem I found using gmock and mocking void(void) method.

class Base {
 public:
  virtual ~Base() {}
};

class Derived : public Base
{
 public:
  void GetValueAndDelete()  { delete this; } //here we crash
};

int main() {
  Derived* p = 0;
  p->GetValueAndDelete();
}

Building it with:

/tools/gcc6.1/bin/g++ --version
g++ (GCC) 6.1.0

with optimization level different than -O0 and running the result causes segmentation fault.

Is it gcc bug or something with c++ code (yes, yes, I know that it uses side effects, but it works with other compilers and without optimization as well)

解决方案

Is it gcc bug

No.

or something with c++ code

Yes. You use the arrow operator on a pointer that doesn't point to a valid object. This has undefined behaviour.

Dereferencing null pointer and calling method in this way that does not use any members is fine.

It's not fine according to the standard. It's UB.

What is calling method on pointer?

Is implementation specific.

Deleting this is nothing special.

Deleting this is very special.

You should only take care of not using any member after

Yes, that and you must make sure that only new was used to create all instances on which the function is ever called. No automatic objects, no static objects no new[], no malloc + placement new.

So yes, you can delete this, but be careful.

这篇关于gcc 6.1.0分段错误 - gcc bug?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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