1

Create a function ft_range which returns an array ofints. This int array should contain all values between min and max. Min included - max excluded.

#include <printf.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>

#include <stdlib.h>

int *ft_range(int min, int max)
{
    int *ptrInt;
    int i;
    int temp;
    temp = min;
    i = 0;
    ptrInt = NULL;
    if (max < min)
    {
        return (ptrInt);
    } else
    {
        ptrInt = malloc(max - min);
    }
    while (i < (max - min))
    {
        *(ptrInt + i) = temp + i;
        i++; /trows segfault at i == 473742332
    }
    return (ptrInt);
}



int *ft_range(int min, int max);

int main()
{
    int i = 0;
    int min = -947483640;
    int max =  947483640;
    int *ptr = ft_range(min, max);

    while (ptr != NULL)
    {
        printf("%d", *ptr);
        printf("%c", '\n');
    }
}

If i put bigger values, segfault throws also on the bigger values. And this code works perfectly on the lower values.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Vladimir
  • 294
  • 1
  • 3
  • 10
  • 4
    `ptrInt = malloc(max - min); **-->>** ptrInt = malloc((max - min) *sizeof *ptrInt);` Also,most people prefer array-notation: `*(ptrInt + i) = temp + i;` **-->>** `ptrInt[i] = temp + i;` – wildplasser Sep 26 '18 at 20:23
  • 1
    You're getting a segfault because you're invoking undefined behavior by writing past the size of the memory region that you've `malloc`ed. `malloc` accepts the number of bytes to allocate. `sizeof int` on your machine is surely larger than one byte, so simply allocating `max - min` bytes is not enough to store that many `int`s. After you fix your segfault, you're going to enter an infinite loop in `main`. `ptr` is never updated in your `while` loop. – yano Sep 26 '18 at 20:28
  • If this is two separate source files, please indicate that. If not, normally all the `#include` directives go at the top of the file. – Keith Thompson Sep 26 '18 at 20:34
  • 1
    @wildplasser thank you, it helped. – Vladimir Sep 26 '18 at 20:36
  • There is also the corner case `min==max` , which is not caught by your check, but resulting in `malloc(0)` – wildplasser Sep 26 '18 at 20:47

1 Answers1

1

Code allocates insufficient memory when int is wider than char - something that is very common.

Allocate based on the size of the pointed to object. @wildplasser

int *ptrInt;
...
  // ptrInt = malloc(max - min);
  ptrInt = malloc(sizeof *ptrInt * (max - min));
  //              ^------------^   ^---------^ number of elements
  //              +------------+-------------- size of 1 element
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256