c - 在我的程序中,为什么“if and else 语句”会遇到分段错误?
问题描述
//这段包含 if 和 else 语句的代码会遇到分段错误(核心转储)
void print(struct node *tail)
{
if (tail == NULL)
{
printf("No node in the list.");
}
else if (tail == tail->next) //If there is only one node.
{
printf("%d", tail->data);
}
struct node *temp = tail->next;
do
{
printf("%d ", temp->data);
temp = temp->next;
} while (temp != tail->next);
printf("\n");
}
下面的代码已更正并运行良好。
上面的代码有什么问题?
void print(struct node *tail)
{
//If there is no node in the list.
if (tail == NULL)
{
printf("No node in the list.");
}
else if (tail == tail->next) //If there is only one node.
{
printf("%d", tail->data);
}
else
{
struct node *temp = tail->next;
do
{
printf("%d ", temp->data);
temp = temp->next;
} while (temp != tail->next);
}
printf("\n");
}
解决方案
第一个代码片段中的问题是,当tail
为 NULL 时,您稍后仍会尝试tail
在代码中取消引用:
if (tail == NULL)
{
printf("No node in the list.");
}
[...]
struct node *temp = tail->next; // Trying to access tail->next when tail is NULL! Boom!
推荐阅读
- azure-data-factory - 使用数据工厂管道填充 Azure 搜索
- javascript - 从主复选框切换一组复选框
- python - Django 部署后无法导入模块
- java - 链表总是执行 else 语句
- asp.net-mvc - 是否可以将 ODataController 控制器添加到 MVC Web 应用程序?
- c++ - 如何有效地读取和存储 1GB 文本文件中的数据?
- list - Prolog中列表内的单独坐标轴
- c++ - 类模板的模板参数推导不适用于 gcc 8.1.0?
- laravel - Laravel 将图像路径附加到对象数组
- kubernetes - 查看对象的所有应用配置