C ++ in G ++ - Segmentation不使用指针时的错误 [英] C++ in G++ - Segmentation Fault when not using pointers

查看:125
本文介绍了C ++ in G ++ - Segmentation不使用指针时的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用G ++编译一些C ++代码。

I'm trying to use G++ to compile some C++ code. It seems to work fine in other compilers, but for whatever reason, G++ won't produce working output.

披露:这是其中一部分。

这是一个破坏性破坏的代码片段:

Here's the snippet that's wreaking havoc:

set<int> t1, t2;

很奇怪,因为下面的代码工作正常:

It's strange because the following code works just fine:

set<int> *t1 = new set<int>();
set<int> *t2 = new set<int>();

授予,我必须使用 - > 而不是,但这是预期。第一个片段在运行时产生分段错误。

Granted, I have to use -> instead of ., but that's expected. The first snippet produces a segmentation fault at runtime. The second does intuitively what I'd expect it to.

无论如何,在后台, .cpp set 具有:

Anyhow, behind the scenes, the .cpp for set has this:

#include <cstdlib>
#include <iostream>

using namespace std;

template <class T>
set<T>::set() : bag<T>() {}

template <class T>
set<T>::set(const set<T>& b) : bag<T>(b) {}

.h 看起来像这样:

#include "bag.h"

template <class T>
class set : public bag<T>
{ 
    public:
        set( );
        set(const set &b);

// ...

};
#include "set.cpp"

最后但并非最不重要的是, bag.cpp bag.h 文件如下所示:

And last but not least, the bag.cpp and bag.h files looks like this:

using namespace std;

template <class T>
bag<T>::bag() {
    head = NULL;
}

template <class T>
bag<T>::bag(const bag<T>& b) {

    // ...

}

bag.h

template <class T>
class bag
{ 
    public:
        bag( );
        bag(const bag &b);

    // ...
};
#include "bag.cpp"

同样,我觉得G ++只是讨厌我,但后来我又可以做一些蠢事。

Again, I feel like G++ just hates me, but then again I could be doing something dumb. Just a simple nudge in the right direction would be great.

推荐答案

这里是一个一般的提示,将使你的生活更轻松万分之一。

Here's a general hint that will make your life a million times easier.

使用-g和-Wall标志编译此程序:

Compile this program with the "-g" and "-Wall" flags:

gcc -g -Wall foo.cpp

信息。 -Wall在编译时会产生额外的警告。然后使用调试器:

The "-g" adds debugging information. The "-Wall" spits out additional warnings when compiling. Then use the debugger:

gdb ./a.out

点击运行启动程序。代码
崩溃后,使用 bt 转储调用堆栈。然后,您可以准确地在代码中查看崩溃发生的位置。

Hit run to start your program. Use bt to dump your call stack once your code crashes. You can then see exactly where the crash is happening in your code.

当你在使用时,google的gdb教程。花一个小时或两个学习如何正确地使用gdb将回报,有兴趣。我答应你。

While you're at it, google "gdb tutorial". Spending an hour or two learning how to use gdb properly will pay itself back, with interest. I promise you.

这篇关于C ++ in G ++ - Segmentation不使用指针时的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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