代码之家  ›  专栏  ›  技术社区  ›  Larry Hart

构造函数中的分段错误

  •  2
  • Larry Hart  · 技术社区  · 12 年前

    这种情况发生在 我试着用C++做的课。从java迁移过来,我发现问题主要是在生成类方面。我运行valgrind,它似乎在构造函数中。

    ==30214== Memcheck, a memory error detector
    ==30214== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
    ==30214== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
    ==30214== Command: ./CoC
    ==30214== 
    ==30214== 
    ==30214== Process terminating with default action of signal 11 (SIGSEGV)
    ==30214==  Bad permissions for mapped region at address 0x404B4F
    ==30214==    at 0x4C2B9EC: strcat (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==30214==    by 0x404220: Model::Model(std::string) (in /home/kronus/Apollo/CoC)
    ==30214==    by 0x402617: main (in /home/kronus/Apollo/CoC)
    

    正如您所看到的,我正试图将这个模型类的构造函数调用到主方法中。这是构造函数的代码

    Model::Model(std::string filename)
    {
    m_TotalFaces = 0;
    m_model = lib3ds_file_load(filename.c_str());
        // If loading the model failed, we throw an exception
        if(!m_model)
        {
               throw strcat("Unable to load ", filename.c_str());
        }
    }
    

    当它被调用时,它会以分段错误结束。重要提示:我已经在头文件中声明了类。这就是我得到错误的时候。我把这个类放在源文件中,它运行得很好。我做错了什么?

    2 回复  |  直到 9 年前
        1
  •  9
  •   autistic    12 年前

    strcat 尝试将第二个参数所指向的字符串写入第一个参数所指字符串的末尾。由于第一个参数是字符串文字(应该被认为是只读的),所以会出现一个令人讨厌的segfault。

    我建议学习C++,就好像它是一个 完全不同的语言 到Java,因为否则你可能会认为 相像的 特征函数 相同的 。这很危险。猴子可以通过在键盘上捏脸来学习Java。C++有未定义的行为,可能在你的机器上正常工作,但在另一台机器上发射核导弹。

        2
  •  2
  •   Community CDub    7 年前

    您正在附加一个错误的常量字符串:

    strcat("Unable to load ", filename.c_str());
             ^ you can't append to constant
    

    阅读以下内容: c++ exception : throwing std::string
    您可能希望避免将字符串用作异常类,因为它们本身可以在使用过程中引发异常。

    第二: What type should I catch if I throw a string literal?