I need to create a function which returns an array ofints. This int array should contain all values between min and max (both included).
- If min >= max a null pointer should be returned.
The question is why when (min = -2147483468) and (max = 2147483647) and len becomes 4294967296 I get "Segmentation fault". My code:
#include <stdlib.h>
#include <stdio.h>
int *ft_range(int min, int max)
{
int *range;
long int len;
long int i;
range = NULL;
if (min >= max)
return (NULL);
len = max - min + 1;
if(!(range = (int *)malloc(sizeof(int) * len)))
return (NULL);
i = 0;
while (min < max)
{
range[i] = min;
min++;
i++;
}
range[i] = max;
return (range);
}
But if I enter (min = -2147483468) and (max = 2147483646) with (len = 4294967295) it works.
len = max - min + 1;-->len = 1L + max - min;to avoidintoverflow whenlongis wider. Better to usesize_t lenand(size_t)1. - chux - Reinstate Monicalong intis is larger thanint, so it's not portable code, but it will work on the OP's system. - ikegami