SIGSEGV Ошибка при запуске функции в C - PullRequest
0 голосов
/ 13 ноября 2018

Я начинаю программировать на C, и во время запуска моей программы на C я получаю странную ошибку:

 Program received signal SIGSEGV, Segmentation fault.
0x0000559625ce4a56 in inputNewCountry (cordinateOfCountry=...) at /home/david/CLionProjects/untitled/Countries.c:40
40    newCountry->cordinateOfCountry.xLeft=cordinateOfCountry.xLeft;

Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.

код моей функции:

Country* inputNewCountry(cordinate cordinateOfCountry)
{
  Country *newCountry;
  newCountry->cordinateOfCountry.xLeft=cordinateOfCountry.xLeft;
    newCountry->cordinateOfCountry.xRight=cordinateOfCountry.xRight;
  newCountry->cordinateOfCountry.yLeft=cordinateOfCountry.yLeft;
    newCountry->cordinateOfCountry.yRight=cordinateOfCountry.yRight;
  newCountry->cities=NULL;
  newCountry->numberOfCities=0;
  return newCountry;
}

"struch cordinate":

typedef struct cordinate
{
    int xLeft,yLeft;
    int xRight,yRight;
}cordinate;

Понятия не имею, что я делаю не так, может кто-нибудь помочь?

1 Ответ

0 голосов
/ 13 ноября 2018
Country *newCountry;

здесь вы определяете переменную неинициализированного указателя.

newCountry->cordinateOfCountry.xLeft=[...]

здесь (в следующей строке) вы записываете данные в смещение (вычисленное cordinateOfCountry.xLeft) в эту переменную неинициализированного указателя, a.k.a. вы записываете данные в случайную точку в памяти.

Вы должны выделить память для newCountry, например, с помощью функции stdlib.h malloc:

Country *newCountry = malloc(sizeof(Country));

Запомните free любую выделенную память таким образом.

Вы также можете выделить глобальную переменную (но будьте осторожны, поскольку вызов функции более одного раза приведет к перезаписи данных):

Country globalCountry;

Country inputNewCountry(cordinate cordinateOfCountry)
{
    Country *newCountry = &globalCountry;
    [...]

Вы можете скрыть глобальную переменную, чтобы она была видна только внутри функции:

Country inputNewCountry(cordinate cordinateOfCountry)
{
    static Country hiddenGlobalCountry; // Other functions cannot see hiddenGlobalCountry, but it still acts like a global variable
    // Note that just Country hiddenGlobalCountry won't work, since such a variable will be destroyed once the function exits (making it little better than writing to uninitialized memory)
    Country *newCountry = &hiddenGlobalCountry;
    [...]

Или вместо этого вы можете просто вернуть страну:

Country inputNewCountry(cordinate cordinateOfCountry)
{
  Country newCountry;
  newCountry.cordinateOfCountry.xLeft=cordinateOfCountry.xLeft;
  newCountry.cordinateOfCountry.xRight=cordinateOfCountry.xRight;
  newCountry.cordinateOfCountry.yLeft=cordinateOfCountry.yLeft;
  newCountry.cordinateOfCountry.yRight=cordinateOfCountry.yRight;
  newCountry.cities=NULL;
  newCountry.numberOfCities=0;
  return newCountry;
}
...