Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7929891
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T20:14:17+00:00 2026-06-03T20:14:17+00:00

I am having a truly bizarre problem with my code here. It works (seemingly)

  • 0

I am having a truly bizarre problem with my code here. It works (seemingly) when I use manual print statements to output the values of int *primesArr, but if I try to do so with a for loop it fails. I ran it through gdb and find that it crashes right around where I set the next cell in the array to value ‘k’, which only occurs when a number is prime. The first iteration is successful (i.e. 2 is set to primesArr[0]) and then the program Segfaults when trying to increment the array. But this only happens when using a for-loop. When I create individual print statements, my program works as expected. I’m not sure how/why I am accessing memory that hasnt been appropriated when using a for-loop. I’m sure I’ve performed some amateur mistake somewhere, and it probably has something to do with how I’m passing my pointer… but I cannot determine its exact root. I’d appreciate any help and thank you in advance.

#include<stdio.h>

int genPrimes(int seed, int *test){
    int inNumPrimes=0;
    for(int k=0; k<=seed; k++){//k is number being checked for primeness
        int cnt=0;
        for(int i=1; i<=k; i++){//'i' is num 'k' is divided by
            if(k%i == 0){
                cnt++;
                if(cnt > 2){
                    break;
                }
                }else{
            }

        }
        if(cnt == 2){
            printf("%i IS PRIME\n",k);
            *test=k;
            test++;//according to gdb, the problem is somewhere between here
            inNumPrimes++;//and here. I'd wager I messed up my pointer somehow
        }
        //printf("%i\n",k);
    }
    return inNumPrimes;
}

int main(){
    int outNumPrimes=0;
    int *primesArr;
    int n = 0;
    n=20;

    outNumPrimes=genPrimes(n, primesArr);
    printf("Congratulations!  There are %i Prime Numbers.\n",outNumPrimes);

    //If you print using this for loop, the SEGFAULT occurs.  Note that it does not matter how high the limit is; its been set to many values other than 5. It will eventually be set to 'outNumPrimes'
    //for(int a=0; a<5; a++){
    //printf("%i\n",primesArr[a]);
    //}

    //If you print the array elements individually, the correct value--a prime number--is printed.  No SEGFAULT.
    printf("%i\n",primesArr[0]);
    printf("%i\n",primesArr[1]);
    printf("%i\n",primesArr[2]);
    printf("%i\n",primesArr[3]);
    printf("%i\n",primesArr[4]);
    printf("%i\n",primesArr[5]);
    printf("%i\n",primesArr[6]);
    printf("%i\n",primesArr[7]);
    //
    return 0;
}

Output with manual statements:

$ ./a.out 
2 IS PRIME
3 IS PRIME
5 IS PRIME
7 IS PRIME
11 IS PRIME
13 IS PRIME
17 IS PRIME
19 IS PRIME
Congratulations!  There are 8 Prime Numbers.
2
3
5
7
11
13
17
19

Now with the for loop:

$ ./a.out 
2 IS PRIME
Segmentation fault
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T20:14:18+00:00Added an answer on June 3, 2026 at 8:14 pm

    The line

    int *primesArr;
    

    Declares primesArr as a pointer variable but doesn’t allocate any memory for it. Since the genPrimes() function expects to treat it as an empty array that will be filled with primes, you can allocate memory in main() before calling genPrimes():

    int primesArr[MAX_PRIMES];
    

    or

    int *primesArr = malloc(MAX_PRIMES * sizeof(int));
    

    In both cases, however, you must guarantee that MAX_PRIMES is large enough to hold all of the primes that genPrimes() finds, otherwise the code will generate an error just as it does now.


    Other hints:

    1: Complexity

    The only reason cnt is necessary is that k is divisible by 1 and k. If you change

    for (int i=1; i<=k; i++) {  // 'i' is the number 'k' is divided by
    

    to

    for (int i=2; i<k; ++i) {  // 'i' is the number 'k' is divided by
    

    then both of those cases are eliminated, and the loop can exit as soon as it finds a value of i for which k%i == 0.

    2: Efficiency

    The test

    for (int i=2; i<k; ++i) {  // 'i' is the number 'k' is divided by
    

    is still quite inefficient for two reasons. First, there’s no need to test every even number; if k > 2 and (k % 2) == 0, then k cannot be prime. So you can eliminate half of the tests by checking explicitly for 2 (prime) or divisibility by 2 (not prime), and then using

    for (int i = 3;  i < k;  i += 2) {  // 'i' is the number 'k' is divided by
    

    But you can make this still more efficient, because you can stop after reaching sqrt(k). Why? If k is divisible by some number i, then it must also be divisible by k/i (because i * k/i=k). And if i > sqrt(k), then k/i < sqrt(k) and the loop would already have exited. So you need only

    int r = (int) sqrt(k);
    for (int i = 3;  i <= r;  i += 2) {  // 'i' is the number 'k' is divided by
    

    If sqrt() isn’t available, you can use

    for (int i = 3;  i*i <= k;  i += 2) {  // 'i' is the number 'k' is divided by
    

    3: Style

    Just a simple thing, but instead of

    int n = 0;
    n=20;
    

    you can simply write

    int n = 20;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is a truly embarrasssing question. I am having a validate script problem and
Having this table: CREATE TABLE `example` ( `id` int(11) unsigned NOT NULL auto_increment, `keywords`
Having a problem with Backbone being inconsistent. I've added a console.log to the fetch
I have to work with some code that isn't truly MVC (i.e., it doesn't
I am having problems with wxpython. When I run the following code, it will
I'm having a truly... bizzare error in none other than Internet Explorer with a
This is probably a truly basic thing that I'm simply having an odd time
I am fairly new at core data and am having a problem. My app
I’m having a problem with translating T-SQL query into Nhibernate query – or writing
so I'm having the most difficult of time pulling values out of an NSDictionary

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.