C++ strange segmentation fault by object creation

2020-06-30 05:31发布

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.

4条回答
【Aperson】
2楼-- · 2020-06-30 06:15

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.

查看更多
家丑人穷心不美
3楼-- · 2020-06-30 06:17

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.

查看更多
干净又极端
4楼-- · 2020-06-30 06:21

Only use -> with pointers.

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

Needs to be

FooClass foo1;
foo1.doSomething();
查看更多
相关推荐>>
5楼-- · 2020-06-30 06:23

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

查看更多
登录 后发表回答