G++ 中的 C++ - 不使用指针时出现分段错误

2022-01-12 00:00:00 segmentation-fault g++ c++

我正在尝试使用 G++ 编译一些 C++ 代码.它似乎在其他编译器中工作正常,但无论出于何种原因,G++ 都不会产生工作输出.

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.

披露:这是家庭作业的一部分,但我觉得这更像是一个编译器问题,因为它适用于其他编译器.

Disclosure: This is part of a homework assignment, but I feel like it's more of a compiler issue, since it works in other compilers.

这是造成严重破坏的片段:

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.

无论如何,在幕后,set.cpp 有这个:

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.cppbag.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

-g"添加调试信息.-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.

当你在它的时候,谷歌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.

相关文章