c - 我的程序收到信号 SIGSEGV,分段错误,请帮忙
问题描述
当我尝试运行这个程序时,它不起作用。当我去调试时,弹出一条消息“程序收到信号sigsegv,分段错误”
我用 gdb 调试程序,这就是消息。程序收到信号 SIGSEGV,分段错误。0x0000555555555195 in ft_atoi (str=0x555555556004 "111") at ft_atoi.c:33 33 while (ft_isspace(str[i]))
#include <string.h>
#include <stdio.h>
static int ft_isspace(char c)
{
if (c == '\n' || c == '\f' || c == ' ' ||
c == '\r' || c == '\v' || c == '\t');
return (1);
return (0);
}
int ft_atoi(const char *str)
{
int i;
int n;
int signe;
n = 0;
i = 0;
signe = 1;
while (ft_isspace(str[i]))
i++;
if (str[i] == '-' || str[i] == '+')
{
if (str[i++] == '-')
signe = -1;
}
while (str[i] >= '0' && (str[i] <= '9') && str[i] != '\0')
{
if (((unsigned long)n > 9223372036854775807 / 10) ||
(((unsigned long)n == 9223372036854775807 / 10) &&
((unsigned long)n % 10) > 7))
return ((signe > 0 ? -1 : 0));
n = n * 10 + (*(str + (i++)) - '0');
}
return (n * signe);
}
int main()
{
printf("%d", ft_atoi("111"));
return 0;
}
解决方案
static int ft_isspace(char c)
{
if (c == '\n' || c == '\f' || c == ' ' ||
c == '\r' || c == '\v' || c == '\t');
return (1);
return (0);
}
这将始终返回 1,导致循环结束。注意这里的分号:
c == '\r' || c == '\v' || c == '\t'); <-- HERE
想象一下,如果它看起来像这样:
c == '\r' || c == '\v' || c == '\t') j=2;
这将导致if
语句决定是否j=2
执行。return
无论if
. _
那么你的代码做同样的事情,除了j=2
你有一个空语句而不是 。
语法是:if <表达式> <语句>
您的表达式以最后一个右括号结束。所以你的受控语句只是;
.
只需删除那个分号,这样return
就是由if
and 控制的语句,它立即出现在表达式之后。
推荐阅读
- java - Java Stream:类 java.util.LinkedHashMap 不能转换为类 RealmRole
- html - CSS - 文本和下拉菜单之间的间距问题
- c++ - GetTokenInformation 在第一次调用中返回 ERROR_INSUFFICIENT_BUFFER
- r - 我在 R 中导入数据集时遇到问题
- docker - Google Cloud Run - 如何为 GCR 指定 docker 命令行参数?
- bash - 如何列出年龄小于特定时期的 Kubernetes pod
- image - 铸就未来
使用 Flutter 转为 base64 图像 - javascript - java脚本的div可见性不起作用
- function - 在 GraphQL 的解析器函数中调用处理函数
- azure - 概述使用哪个 Azure 个人访问令牌的时间和频率?