Segmentation Fault with malloc

0

Good morning! I'm doing a program, and in a part of it I need to create a vector full of zeros the size of the range entered by the user:

scanf("%ld %ld", &n1, &n2);
int *vetor; 
vetor = malloc((n2 - n1 + 1) * sizeof(long int));
for (long int k = 0; k <= n2; k++)
{
    vetor[k] = 0;
}

However, when I type some intervals, such as 100000000, the segmentation fault program is right up front, what can it be?

    
asked by anonymous 25.08.2018 / 13:06

2 answers

2

Use calloc() and be happy.

scanf("%ld %ld", &n1, &n2);
int *vetor = calloc((n2 - n1 + 1) * sizeof(long int));

When accessing the elements of the vector do not use the <= operator, use only < , as it starts at 0, the last element is the size - 1, same as you do to count 10 number starting from 0, you go to 9.

    
25.08.2018 / 17:26
1
scanf("%ld %ld", &n1, &n2);
int *vetor;
vetor = malloc(abs(n2 - n1+1) * sizeof(long int));
for ( k = 0; k <= abs(n2-n1); k++)
{
    vetor[k]=0;
}

I think I wanted to do this, you have to put abs() because if we insert n1=100 and n2=1 would generate a negative number, which we do not want, then we use the module.

Another way was to use the calloc function as already mentioned, but using the module.

int *vetor = calloc(abs(n2 - n1 + 1) * sizeof(long int));

    
25.08.2018 / 19:40