int *rrange(int start, int end);
I was asked, to write a function and allocate with malloc an array of integers, fill it with consecutive
values that begin at end and end at start (Including start and end !), then
return a pointer to the first value of the array. The functions works with small numbers, when tested with big numbers I get seg fault
. And I think I got seg fault
due to reaching the limit of int
. How can I solve this issue?.
/*- With (1, 3) you will return an array containing 3, 2 and 1
- With (-1, 2) you will return an array containing 2, 1, 0 and -1.
- With (0, 0) you will return an array containing 0.
- With (0, -3) you will return an array containing -3, -2, -1 and 0.*/
#include <stdlib.h>
int *rrange(int start, int end)
{
int *range;
int i;
i = 0;
range = (int *)malloc(sizeof(int *));
if (end <= start)
{
while (end <= start)
range[i++] = end++;
}
else
{
while (end >= start)
range[i++] = end--;
}
return (range);
}
= Test 1 ===================================================
$> ./pw53y11cbachacu14eue5cab
$> diff -U 3 user_output_test1 test1.output | cat -e
Diff OK :D
= Test 2 ===================================================
$> ./o1jrm4t3vqengizvj1tlwab4 "21" "2313" "12"
$> diff -U 3 user_output_test2 test2.output | cat -e
Diff OK :D
= Test 3 ===================================================
$> ./usl3i1tc1xv9tr1gs9n5x5vr "2147483647" "2147483640" "7"
$> diff -U 3 user_output_test3 test3.output | cat -e
--- user_output_test3 2016-06-08 16:26:16.000000000 +0200$
+++ test3.output 2016-06-08 16:26:16.000000000 +0200$
@@ -1,8 +1,8 @@$
-0$
-0$
-0$
-0$
-0$
-0$
-0$
+2147483640$
+2147483641$
+2147483642$
+2147483643$
+2147483644$
+2147483645$
+2147483646$
$
Diff KO :(
Grade: 0
= Final grade: 0 ===============================================================