Y
Y
Yarik Mamaev2018-12-13 02:10:05
C++ / C#
Yarik Mamaev, 2018-12-13 02:10:05

How to fix segmentation error?

I screwed up somewhere with pointers and can't find where. Here is the code

#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstring>

using namespace std;

struct poezd
{
  char* fio;		// Пассажир
  char* point_from;	// Пункт отправления
  char* point_to;		// Пункт прибытия
  double price;		// Цена билета
};

vector <poezd> one;

poezd push_bilet(int* n);		// Функция заталкивания пассажира в базу данных с билетами - покупка билета

void help();						// Команда-функция-хэлпер

int main()
{
  setlocale(LC_ALL,"RU");

  int n=0;		// Кол-во пассажиров в поезде

  cout<<"Вас приветствует веселый кондуктор. Чтобы выйти из программы введите exit. Для получения справки воспользуйтесь --help. Приятной работы!"<<"/n";
  
  char* command;		
  while(strcmp(command, "exit") == 1);
  {
    cout<<"~shell>> ";
    cin>>*command;

    if(strcmp(command, "--help") == 0)
    {
      help();
    }
    
    if(strcmp(command, "new_persone") ==0)
    {
      push_bilet(&n);
    }	
    
  }
}

poezd push_bilet(int* n)
{	
  poezd neki;		// neki - это объект структуры poezd он создается каждый раз при вызове 
  cout<<"Введите Имя, Фамилию, Отчество/n"<<"~new>> "<<"/n";
  cin>> one.at(*n).fio;

  cout<<"Введите пункт отправления/n"<<"~new>> "<<"/n";
  cin>> one.at(*n).point_from;

  cout<<"Введите пункт назначения/n"<<"~new>> "<<"/n";
  cin>> one.at(*n).point_to;

  cout<<"Введите цену билета/n"<<"~new>> "<<"/n";
  cin>> one.at(*n).price;
}

void help()
{
  cout<<"--help - помощь по шел коду";
  cout<<"new_persone - новый человек - новый билет";
}

gdb gives the following
(gdb) run
Starting program: /root/a.out 

Program received signal SIGSEGV, Segmentation fault.
__strcmp_ssse3 () at ../sysdeps/x86_64/multiarch/../strcmp.S:173
173	../sysdeps/x86_64/multiarch/../strcmp.S: Нет такого файла или каталога.
(gdb)

PS One more little question! How to change the call to the push_bilet function if the vector is vector <poezd> one;declared inside the main body, and how then to return the vector instance from there?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-12-13
@jcmvbkbc

gdb gives the following

It remains to learn how the gdb bt, up, down and frame commands work, and you can answer your own question.
But in this case, everything is clear:
char* command;		
  while(strcmp(command, "exit") == 1);

Three errors on two lines: first, command is not initialized at the time strcmp is called, and this calls SEGFAULT.
Second, strcmp returns 0 if equal, <0 or >0 (not necessarily 1) if the strings are not equal.
Thirdly ';' after the while () is clearly superfluous.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question