exsnake
exsnake

Reputation: 1823

Dynamic memory array crash the executable

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?

Upvotes: 1

Views: 77

Answers (2)

paxdiablo
paxdiablo

Reputation: 882028

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".

Upvotes: 2

metacubed
metacubed

Reputation: 7281

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.

Upvotes: 3

Related Questions