开发者

C++ strange segmentation fault by object creation

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.


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.


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.


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


Only use -> with pointers.

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

Needs to be

FooClass foo1;
foo1.doSomething();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜