c ++类中运行时的分段错误

时间:2013-05-24 10:48:03

标签: c++ stl

嗨,我在运行以下代码时看到此错误。 “分段错误(核心倾销)”我不能理解。\有人帮助我。感谢

#ifndef __LIB_TAG_STRINGS_H__
#define __LIB_TAG_STRINGS_H__

//============
//stl
#include <deps.h>
#include <string>
namespace tags
 {
   const std::string tag1 ("TAG_1");
   const std::string tag2 ("TAG_2");
 }//END namespace TAGS

namespace attributes
 {
  const std::string attribute1 ("ATTRIBUTE_1");
  const std::string attribute2("ATTRIBUTE_2");
 }

class _Name 
 {
  public:

  _Name ()
   {
    /**This constructor is used to map some tags with the strings**/
    string_map.insert (std::make_pair (std::string ("TAGNOTE1"), tags::tag1 ));
    string_map.insert (std::make_pair (std::string ("TAGNOTE2"), tags::tag2 ));
   };

 const std::string& getName (const std::string& class_name) const
   {   
    std::map<std::string, std::string>::const_iterator i = string_map.find(class_name);
    return (i != string_map.end ()) ? i->second : null_string;
  }


   private:
    std::map<std::string, std::string> string_map;
    std::string null_string;
 };

namespace Name
 {
  const _Name NAME;
 }
#endif

核心在运行时被转储。这是GDB指向错误的代码。

GDB日志:

Program received signal SIGSEGV, Segmentation fault.
0x0000003b00e9d23b in std::basic_string, std::allocator >::basic_string(std::basic_string, std::allocator > const&) () from /usr/lib64/libstdc++.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.80.el6.x86_64 libaio-0.3.107-10.el6.x86_64 libgcc-4.4.6-4.el6.x86_64 libstdc++-4.4.6-4.el6.x86_64 nss-softokn-freebl-3.12.9-11.el6.x86_64 openssl-1.0.0-20.el6_2.5.x86_64 zlib-1.2.3-27.el6.x86_64
(gdb) where
0  0x000strong text0003b00e9d23b in std::basic_string, std::allocator >::basic_string(std::basic_string, std::allocator > const&) () from /usr/lib64/libstdc++.so.6
1  0x00007ffff1375372 in _Name::_Name (this=0x7ffff15a9b60)
    at /prog/lib/tag_strings.h:229
2  0x00007ffff139581b in __static_initialization_and_destruction_0 ()
    at /prog/lib/tag_strings.h:257
3  global constructors keyed to dest.cxx(void) () at dest.cxx:679
4  0x00007ffff1398516 in __do_global_ctors_aux () from ./dest.so
5  0x00007ffff135a2bb in _init () from ./dest.so
6  0x00007fffe361f000 in ?? ()
7  0x0000003af860e535 in _dl_init_internal () from /lib64/ld-linux-x86-64.so.2
8  0x0000003af8600b3a in _dl_start_user () from /lib64/ld-linux-x86-64.so.2
9  0x0000000000000001 in ?? ()
10 0x00007fffffffe128 in ?? ().
11 0x0000000000000000 in ?? ().

1 个答案:

答案 0 :(得分:1)

在我看来就像是一个静态的初始化订单问题。

构建NAME对象时,它会访问tag1 / tag2对象 - 但不能保证这些对象已构建完毕!

您可以尝试更改依赖于函数的对象。

namespace tags {
    static std::string tag1() { return std::string("TAG1"); }
    ...
}

...
string_map.insert (std::make_pair (std::string ("TAGNOTE1"), tags::tag1() ));
...