Reputation: 13
When I try to run this program, it doesn't work. When I go to debugs, a message pops up "program received signal sigsegv, segmentation fault"
i debug the programe with gdb, and this is the messages. Program received signal SIGSEGV, Segmentation fault. 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;
}
Upvotes: 1
Views: 1259
Reputation: 182769
static int ft_isspace(char c)
{
if (c == '\n' || c == '\f' || c == ' ' ||
c == '\r' || c == '\v' || c == '\t');
return (1);
return (0);
}
This will always return 1, causing the loop to run off the end. Notice the semicolon here:
c == '\r' || c == '\v' || c == '\t'); <-- HERE
Imagine if it looked like this:
c == '\r' || c == '\v' || c == '\t') j=2;
That would cause the if
statement to decide whether j=2
is executed. And the return
on the next line would execute regardless of the results of the if
.
Well your code does that same thing, except instead of j=2
, you have an empty statement.
The syntax is: if <expression> <statement>
Your expression ends with that last close parenthesis. So your controlled statement is just the ;
.
Just remove that semicolon so the return
is the statement that is controlled by the if
and that appears immediately after the expression.
Upvotes: 1