SIGSEGV在C中运行功能时出错

时间:2018-11-12 22:27:42

标签: c function struct typedef

我开始使用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;
}

“支柱坐标”:

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

我不知道我在做什么错,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

Country *newCountry;

在这里定义一个未初始化的指针变量。

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

在这里(在下一行中)将数据写入到此未初始化的指针变量的偏移量(由cordinateOfCountry.xLeft计算),也就是将数据写入内存中的随机点。

您应该为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;
}