1

I have this code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{

    int num,i,k,tamano,cont=0;

    int *prim;
    scanf("%d",&num);
    num=num+1;
    prim = malloc(num * sizeof(int));


    for(i=1;i<num;i++)
        prim[i] = 1;

    for(i=2;i<=sqrt(num);i++){
        if((prim[i])!=0 ){
        for(k=2;i*k<num;k++)
                prim[k*i]=0;
        }
    }

    for(i=2;i<num;i++)
        if(prim[i])
            printf("%5d",i);

free(num);
}

This code is for determinate the prime numbers from 2 to num, using the Sieve of Eratosthenes algorithm.

But I have a problem, when I put a number like 15 the executable crash, I don't know what is the problem. If I use a static array the program works perfect, but when I put the dynamic thing the executable crash with no apparent reason.

What can it be?

4
  • 3
    free(num); On no. Are you sure it's not a typo for free(prim);? Commented Aug 15, 2014 at 3:01
  • I'm surprised your compiler didn't give you at least a warning. Commented Aug 15, 2014 at 3:09
  • code::blocks... what can i use instead that one? Commented Aug 15, 2014 at 3:13
  • THe program works fine now! thank you all! Commented Aug 15, 2014 at 3:14

2 Answers 2

3

You are freeing the integer num instead of the pointer prim. Your last statement should be:

free(prim);

Freeing the integer will cause the run-time to interpret the integer value as a memory address and try to access it. This causes unknown behavior to execute, most probably a protected memory violation, which crashes the program.

Sign up to request clarification or add additional context in comments.

Comments

2

You are allocating prim then freeing num.

You should only attempt to free things that have been allocated.

The final line should be changed to:

free (prim);

A good compiler will generally warn you about this, along the lines of "Trying to free a variable that isn't a pointer".

2 Comments

is code::blocks, there is another one better than that one?
Code blocks is an IDE, I believe it uses gcc under the covers which is pretty good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.