I don’t understand why my function segfault if I don’t create a *cpy and tried to work on *tab in my main without it.
#include <stdio.h>
#include <stdlib.h>
int ft_ultimate_range(int **range, int min, int max)
{
int i;
i = 0;
if (min >= max)
return (0);
*range = malloc(sizeof(**range) * (max - min));
if (!*range)
return (-1);
while (min < max)
{
*range[i] = min;
min++;
i++;
}
return (i);
}
// int ft_ultimate_range(int **range, int min, int max)
// {
// int i;
// int *cpy;
// i = 0;
// if (min >= max)
// return (0);
// cpy = malloc(sizeof(cpy) * (max - min));
// if (!cpy)
// return (-1);
// while (min < max)
// {
// cpy[i] = min;
// min++;
// i++;
// }
// *range = cpy;
// return (i);
// }
int main(void)
{
int *tab;
int min = 10;
int max = 20;
int i = 0;
int ret = 0;
ret = ft_ultimate_range(&tab, min, max);
while (i < max - min)
{
printf("tab[%d] = %dn", i, tab[i]);
i++;
}
printf("ret = %dn", ret);
free(tab);
return (0);
}
Why my 1st function segfault, and the 2nd one work ?
If someone can explain me with some details I will apreciate it.
Thx for your help…
New contributor
Plaket is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.