2

This happens with EVERY class I try to make in C++. Migrating from java, I find problems mainly in making classes. I run valgrind and it's in the constructor, it appears to be.

==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)

As you can see I'm trying to call the constructor of this model class into the main method. Here's the code for the constructor

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());
    }
}

When it's called it closes with a segmentation fault. Important: I have declared the class inside the header file. This is when I get the error. I put the class inside the source file and it runs fine. What am I doing wrong?

4

2 回答 2

9

strcat尝试将第二个参数指向的字符串写在第一个参数指向的字符串的末尾。由于第一个参数是一个字符串文字(应该被认为是只读的),你会得到一个讨厌的段错误。

我建议学习 C++,就好像它是一种与 Java完全不同的语言,否则你可能会认为相似的特性功能相同。那很危险。猴子可以通过在键盘上捣碎它的脸来学习 Java。C++ 具有未定义的行为,它可能在您的机器上看起来正常运行,但在另一台机器上发射核导弹。

于 2013-03-24T06:41:00.097 回答
2

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

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

请阅读:c++ 异常:抛出 std::string
您可能希望避免将字符串用作异常类,因为它们本身可以在使用过程中抛出异常。

第二:如果我抛出一个字符串文字,我应该捕获什么类型?

于 2013-03-24T06:39:56.243 回答