문제

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?

도움이 되었습니까?

해결책

strcat attempts to write the string pointed to by the second argument at the end of the string pointed to by the first argument. Since the first argument is a string literal (which should be considered read only), you get a nasty segfault.

I suggest learning C++ as though it's an entirely different language to Java, because otherwise you may think that similar features function the same. That's dangerous. A monkey can learn Java by mashing it's face on the keyboard. C++ has undefined behaviour which may appear to function correctly on your machine, but launch nuclear missiles on another.

다른 팁

You are appending to a constant string that is wrong:

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

Read this: c++ exception : throwing std::string
You may want to avoid using strings as exception classes because they themselves can throw an exception during use.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top