I need to create a function which returns an array of ints. 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); } int main(void) { int max; int min; long int len; int *range; long int i; max = 2147483647; min = -2147483648; if (max != min) len = max - min + 1; else len = 0; i = 0; range = ft_range(min, max); while (i < len) { printf("%d", range[i]); i++; } free(range); return (0); } 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.long intis is larger thanint, so it's not portable code, but it will work on the OP's system.main).long long int.min = -2147483648;withmin = -2147483647 - 1;to avoid UB.