gpt4 book ai didi

c - SIGSEGV 在 C 中运行函数时出错

转载 作者:行者123 更新时间:2023-11-30 19:03:58 26 4
gpt4 key购买 nike

我是 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;
}

“拉伸(stretch)坐标”:

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

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

最佳答案

Country *newCountry;

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

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

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

您应该为 newCountry 分配内存,例如使用 stdlib.h 函数 malloc:

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

请记住以这种方式释放任何已分配的内存。

您还可以分配一个全局变量(但要小心,因为多次调用该函数会覆盖数据):

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;
}

关于c - SIGSEGV 在 C 中运行函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53271003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com