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?
free(num);On no. Are you sure it's not a typo forfree(prim);?