1

我有一个map<key_t, struct tr_n_t*> nodeTable并且我正在尝试执行nodeTable[a] = someNodewhere ais of typetypedef long key_tsomeNodeis of type o_t*

在 stl_function.h 的执行中,我在以下点遇到分段错误:

  /// One of the @link comparison_functors comparison functors@endlink.
  template<typename _Tp>
    struct less : public binary_function<_Tp, _Tp, bool>
    {
      bool
      operator()(const _Tp& __x, const _Tp& __y) const
      { return __x < __y; }
    };

源代码:

#include <stdio.h>
#include <stdlib.h>
#include <map>

using namespace std;

typedef long key_t;

typedef struct tr_n_t {
    key_t key;
    map<key_t, struct tr_n_t *> nodeTable;
} o_t;

int main() {
    o_t *o = (o_t *) malloc(sizeof(o_t));
    o->nodeTable[1] = o;
    return 0;
}

我没有正确使用地图吗?

4

3 回答 3

1

问题是因为你使用 malloc 初始化 o,它的内存被分配了,但它的构造函数没有被调用。

将其更改为,o_t *o = new o_t();因为使用new而不是malloc将调用地图的构造函数。

于 2012-11-10T11:38:28.733 回答
0

您正在为 分配空间o_t,但没有初始化内存。试试这个:

#include <map>

typedef long key_t;

struct o_t {
    key_t key;
    std::map<key_t, o_t*> nodeTable;
};

int main() {
    o_t o;
    o.nodeTable[1] = &o;
    return 0;
}
于 2012-11-10T11:38:04.707 回答
0

您正在使用 C 样式malloc分配包含 C++ 类的结构。没有std::map调用 的构造函数,因此该对象无效。您不能将 malloc 与普通结构一起使用,但不能在需要正确初始化才能工作的对象上使用。

尝试将分配更改为

o_t *o = new o_t();
于 2012-11-10T11:38:27.187 回答