Segmentation Fault with malloc()

Asked

Viewed 85 times

0

In one part of my program I need to create a vector full of zeros the size of the user’s interval:

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;
}

But when I type in a few ranges, like 10 1000000, the program gives Segmentation fault right away, what can be?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

2

Use the calloc() and be happy.

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

I put in the Github for future reference.

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

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 it this way, we need to put the abs() because if we insert n1=100 and n2=1 would generate a negative number, which we don’t want, so we use the module.

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

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

  • Good answer, but I think there should be more emphasis on the logic error of the OP, which put in "for" the condition "k <= N2" when it should be "k < (N2 - n1 + 1)". In C it is more idiomatic to use "<" instead of "<=" when traversing an array. (I would even create a working variable "int Nelems = N2 - n1 + 1" to make the code clearer).

  • I didn’t quite understand that, I’ve seen code to use <= or just < we should not have the flexibility to understand this?

  • 1

    the problem is that the OP used "k <= N2" when you should use "k <= (N2-n1)" as you did (discounting the improvement of abs)...the question of "<=" x "<" is that it is more common to use "<" in C, in these places

  • @zentrunix ah yes correct, nor noticed that he had used the k<=n2 isolated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.