I have to create a given function that allows me to convert a given string (homemade @atoi) of numbers, to a given base (2,8,16, etc) and returns the result: assignment
Problem is that I thought my function was okay but then it gets SIGABORTs everywhere, because indeed, I cant seem to initialize the INT[] with a valid size.
This is my code
#include <stdio.h>
int ft_atoi(char *str)
{
int i;
int sign;
int num;
i = -1;
sign = 1;
num = 0;
while (str[++i] < '0' || str[i] > '9')
if (str[i] == '-')
sign *= -1;
while (str[i] >= '0' && str[i] <= '9')
num = num * 10 + str[i++] - '0';
return (num * sign);
}
int check_base(char *base)
{
int i;
int z;
i = -1;
z = 0;
if (base[0] == '\0' || base[1] == '\0')
return (0);
while (base[++i])
{
z = i + 1;
if (base[i] == '+' || base[i] == '-')
return (0);
if (base[i] < 32 || base[i] > 126)
return (0);
while (base[z++])
{
if (base[i] == base[z])
return (0);
}
}
return (1);
}
int ft_putnbr_base(int nbr, char *base)
{
int size_base;
int nbr_final[(sizeof(int))]; *// I think that this is the troublemaker*
int i;
int final;
i = 0;
final = 0;
size_base = 0;
if (check_base(base))
{
if (nbr < 0)
nbr = -nbr;
while (base[size_base])
size_base++;
while (nbr)
{
nbr_final[i++] = nbr % size_base;
nbr = nbr / size_base;
}
while (--i >= 0)
final = final * 10 + nbr_final[i];
}
return (final);
}
int ft_atoi_base(char *str, char *base)
{
return (ft_putnbr_base(ft_atoi(str), base));
}
int main(void)
{
printf("%d", ft_atoi_base("10", "01")); *// <== Here is where trouble begins, as soon as **str** starts to grow it fails*
}
I did try to use valgrind and gdb with little to no success (since I'm not assinging memory willingly?)
I copied your code, cleaned up a couple of comments that wouldn't let me compile the code, compiled the code, and then ran the example. The sample code as is did run without any program dump. However, when I increased the size of the value to the following:
I got a stack smashing error, meaning that some statement was filling in an array past its bounds.
Reviewing the code I saw that you marked a line of code as being suspect.
And, your suspicions would be correct.
I added a couple of printf statements to act as a terminal level debugger to follow the processing of the integer value that was derived from the string in the ft_putnumber_base function.
With that, I reran the code with the larger integer number and produced this terminal output.
My guess is that there might be more issues with this code, but that was the primary one that stood out. Concentrate there first and see if you can progress.