Engincan Vergili
Engincan Vergili

Reputation: 17

How can I fix .exe stopped working error?

Hello.I am trying to print prime numbers 1 to input but I can get input for maximum 16.When I get input more than 16 I am getting exe error.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *sayilar;
    int *dizi;
    dizi = (int*)malloc( sizeof(dizi));
    int dizi_index=0;
    int i,j;

    printf("ASAL SAYI BULMA PROGRAMI\n");
    input_tekrar:
    printf("Lutfen hangi sayiya kadar asal sayi bulmak istediginizi yaziniz:");
    int input;
    scanf("%d",&input);
    if(input<2){
        printf("\nLutfen daha buyuk bir deger giriniz.\n");
        goto input_tekrar;
    }

    for(i=2;i<=input;i++)
    {
        int c=0;
        for(j=1;j<=i;j++)
        {
            if(i%j==0)
            {
                c++;
            }
        }

       if(c==2)
        {
            *(dizi+dizi_index)=i;
            dizi_index++;
            printf("%d ",i);
        }
    }

    sayilar = fopen("asalsayilar.txt","w");

    for(int sayi=0;sayi<dizi_index;sayi++){
        fprintf(sayilar,"%d  ",*(dizi+sayi));
    }

    free(dizi);

    return 0;
}

How can I print bigger numbers for this program? Is the problem related to memory?  

Upvotes: 0

Views: 55

Answers (1)

user13692250
user13692250

Reputation:

I'm guessing you want an array dizi that stores prime numbers.

dizi = (int*)malloc( sizeof(dizi)); allocates a buffer whose size is sizeof(dizi). dizi is a pointer, so its size may be 4 or 8, depending on your operating system or which architecture you are compiling for (32-bit or 64-bit). Either way, this is not want you want.

The problem occurs in this line

*(dizi+dizi_index)=i;

Here, you are accessing memory that has not been allocated for dizi, so you are getting a memory error. To fix this, allocate dizi with sufficient memory that can store, say input number of ints, because the number of primes from 1 to n is guaranteed to be less than n.

Upvotes: 1

Related Questions