Search code examples
c++segmentation-faulttinyxml

Strange segfault with tinyxml2


I've a segfault that I don't understand. It always occurs at i = 0 and j between 1000 and 1100. Here is the backtrace and all the sources required to see the problem: https://gist.github.com/Quent42340/7592902

Please help me.

EDIT: Oh I forgot. On my gist map.cpp:72 is commented. It's commented in my source code too. I did that to see where the problem came from, but even without that line, the problem is still here.


Solution

  • I see you allocate an array of pointers here:

    m_data = new u16*[m_layers];
    

    But, I never see you allocate the second dimension to this array. It seems like you ought to allocate the rows of your map, either as one large chunk of memory that you separate into chunks yourself, or new each row.

    For example, if you add one line to your for (i ...) loop:

    for(u8 i = 0 ; i < m_layers ; i++) {
            m_data[i] = new u16[m_width * m_height];
    

    If you go that route, you'll also need to upgrade your destructor:

        Map::~Map() {
    
            // WARNING:  This doesn't handle the case where the map failed to load... 
            // Exercise for the reader.
            for (u8 i = 0; i < m_layers; i++) {
                delete[] m_data[i];
            }  
            delete[] m_data;
        }
    

    An alternate approach would be to use std::array and let the C++ standard library manage that for you.