Ошибка сегмента, нужна помощь в чтении дампа ядра - PullRequest
0 голосов
/ 17 апреля 2011

У меня есть ошибка с присваиванием, из-за которого я получаю ошибку сегмента, что при чтении дампа ядра выдает следующее:

#0  0xb781eb27 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::size() const () from /usr/lib/libstdc++.so.6

Это фрагмент кода, на который, я полагаю, он ссылается.

bool flightmap::GetNextCity(int& index, int& nextCity){
    bool success = false;
    flightRec tmp, tmp2;
    for (int i = nextCity; (!success) && (i < size); i++)
    {//if Citytmp goes over size, we never found it
        tmp.DestinationCity = GetCityName(i);
        tmp2 = map[index].Retrieve(tmp,success);
    }//end for loop
    if (success)
    {
        nextCity = GetCityNumber(tmp2.DestinationCity);
    }//end if
    return success;
}

Вот функция Retrieve:

flightRec sortedListClass::Retrieve(flightRec& input, bool& success) const{
    nodeptr curr;
    flightRec tmp;
    curr = head;
    if (head == NULL)
    {//If the list is empty
        std::cout << "List empty, operation not preformed" << std::endl;
        success = false;
    }
    /*LINE 167*/ while ((curr!=NULL)&&(!(curr->DestinationCity==input.DestinationCity))) //<- THIS IS LINE 167
    {//Here we first check if curr points to NULL, then we see if DesinationCity and Origin are not yet found.
        curr=curr->ptr;
    }
    if ((curr->DestinationCity==input.DestinationCity))
    {//If we found it, then let's return it...
        tmp.DestinationCity=curr->DestinationCity;
        //tmp.Origin=curr->Origin;
        tmp.flightnumber=curr->flightnumber;
        tmp.cost=curr->cost;
        success = true;
        return tmp;
    }
    else //We didn't and then...damn.
    {
        //std::cout << "Can't find flight to " << input.DestinationCity << std::endl;
        success = false;
    }
}

flightRec:

struct flightRec{
    std::string Origin;
    int flightnumber;
    float cost;
    std::string DestinationCity;
    bool operator <(const flightRec& rhs) const;
    bool operator ==(const flightRec& rhs) const;
    flightRec* ptr;
};
typedef flightRec* nodeptr;

flightMap.h

#ifndef FLIGHTMAP_H
#define FLIGHTMAP_H
#include "sortedListClass.h"
#include "stackClass.h"
#include <fstream>
#include <cstdio>

class flightmap {
public:
    flightmap();
    flightmap(const flightmap& orig);
    virtual ~flightmap();
    void readcities (std::ifstream& in);
    void readflights (std::ifstream& in);
    void display ();
    void isPath (int& in, int& out);
    void MarkVisited (int& index);
    bool IsVisited (int& index);
    void UnvisitAll ();
    bool GetNextCity (int& index, int& nextCity);
    int GetCityNumber(std::string& city);
    std::string GetCityName(int& index);
private:
    int size;
    sortedListClass* map;
    std::string* origin;
    bool* visited;
};

#endif

После ввода bt вGDB это то, что было на выходе:

#0  0xb7f4eb27 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::size() const () from /usr/lib/libstdc++.so.6
#1  0x0804a407 in std::operator==<char> (__lhs=..., __rhs=...) at /usr/lib/gcc/i686-pc-linux-gnu/4.5.2/../../../../include/c++/4.5.2/bits/basic_string.h:2345
#2  0x0804ab32 in sortedListClass::Retrieve (this=0x8053468, input=..., success=@0xbffff0a3) at sortedListClass.cpp:167
#3  0x0804a1ff in flightmap::GetNextCity (this=0xbffff4dc, index=@0xbffff108, nextCity=@0xbffff104) at flightMap.cpp:197
#4  0x08049ba7 in flightmap::isPath (this=0xbffff4dc, in=@0xbffff164, out=@0xbffff160) at flightMap.cpp:110
#5  0x08049314 in FindPath (datafile=..., map=...) at ola6.cpp:51
#6  0x08049190 in main (argc=2, argv=0xbffff5b4) at ola6.cpp:35

Ответы [ 2 ]

1 голос
/ 17 апреля 2011

bt правильно для обратной трассировки. Вы можете видеть, что ошибка начинается в sortedListClass::Retrieve строке 167. Следующая запись в backtrace (возвращаемая до # 0) предназначена для оператора ==, что означает, что == в строке 167 является причиной сбоя.

В коде, который вы опубликовали, есть несколько == вызовов, поэтому, если вы можете отредактировать свое сообщение и указать, какая строка является строкой 167, мы можем провести дальнейшую диагностику.

Обновление после добавления номера строки:

Это всего лишь предположение, но, возможно, вы забыли установить для элемента ptr значение NULL в какой-то момент ранее в программе, чтобы в этом цикле вокруг строки 167-168 curr в конечном итоге указывалось на случайное ячейка памяти, вызывающая сбой. Возможно также, что объект в этом месте памяти был освобожден, но ptr не был обновлен и указывает на удаленный объект. Внимательно проверьте свой код в местах размещения новых объектов flightRec и убедитесь, что вы всегда правильно устанавливаете ptr.

0 голосов
/ 17 апреля 2011

Где size объявлено / определено в вашем коде?

Похоже, что вы каким-то образом вызываете метод std :: basic_string size.

...