C++ strange segmentation fault by object creation

心不动则不痛 提交于 2019-12-05 08:15:09

问题


I have a strange problem by initiating a class object. The problem is as strange as well not easily reproducible. However I will try to give an indicating example. I have inheritance classes.

class BarClass {
public:
   BarClass() {
      ...
   }
   BarClass(int i, int j) {
      ...
   }
   void doSomething() { ... }
};
class FooClass : public BarClass {
public:
   FooClass() {
   }
   FooClass(int i, int j) : BarClass(i,j) {
      ...
   }
};

Sometime if I initiate objects with following manner, I will get segmentation fault error by initialization.

FooClass foo1;
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();

If I use explicit pointer new, then it is OK..

FooClass *foo1= new FooClass();
foo1->doSomething();
FooClass foo2(10, 20);
foo2.doSomething();

The following code will give me a compiler error on line 2.

FooClass foo1();
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();

how should I properly initiate a object, especially when it has default constructor and those with arguments.


回答1:


Your last issue first...

FooClass foo1();

does not create an object of type FooClass but declares a function called foo1() that takes no parameters and returns a FooClass. Remove the parentheses to create the instance as you did in the first code sample.

why you get a segmmentation fault may have something to do with your destructor which we can't see, and this doesn't get invoked in your second example which leaks.




回答2:


You probably have some bug in your constructor or in doSomething(). Without knowing what happens in these functions there is no way to say what exactly that bug is.




回答3:


Most likely sizeof(YourClass) is too large for the stack, which would explain why only heap allocation succeeds.




回答4:


Only use -> with pointers.

FooClass foo1();
foo1->doSomething();

Needs to be

FooClass foo1;
foo1.doSomething();


来源:https://stackoverflow.com/questions/4106052/c-strange-segmentation-fault-by-object-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!