Vicgi
Vicgi

Reputation: 1

Exception thrown: read access violation this. was nullptr

I tried to work with the points but nothing I do seem to work.

Essentially this will be run in main and a number n is inserted to find all the prime numbers from 0 to n. This is then written into a csv file.

The IDE also says that j is a null pointer.

#include <iostream>
#include "Prime.h"
#include <fstream>


using namespace std;

bool IsInteger(double d) {

    return(d == (int)d);
}

int ComputePrimes(int primes[], int max) {
    int numprimes = 1;
    primes[0] = 2;

    

    for (int i = 3; i <= max; i++) {

        int* j = 0;
        
        bool prime = true;

        while ((prime == true) && (primes[*j] <= (i / 2))) { ///The j is has problems
            
        if (IsInteger((double)i / (double)primes[*j])) {
            
            prime = false;
        
                
            }
        j++;
        }
        if (prime) {
            primes[numprimes++] = i;

        }
    }
    return numprimes;
}

void PrintPrimes(int numprimes, int primes[], string filename) {

    fstream outfile;

    outfile.open(filename);

    for (int i = 0; i < numprimes; i++) {

        outfile << primes[i] << endl;

    }

}

What needs to be changed?

Upvotes: 0

Views: 88

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

You declared the pointer j as a null pointer

int* j = 0;

The above declaration is equivalent to

int* j = nullptr;

So dereferencing the null pointer in this while loop

while ((prime == true) && (primes[*j] <= (i / 2))) {
                                 ^^^^

invokes undefined behavior.

What you get is what you do.

It seems you need to declare j as having at least the type int

int j = 0;

and yp write

while ((prime == true) && (primes[j] <= (i / 2))) {

and so on.

Also this if statement (if change the expression primes[*j] to primes [j])

    if (IsInteger((double)i / (double)primes[j])) {
        
        prime = false;
    
            
        }

does not make a great sense. It would be simpler to write

    if ( i % primes[j] == 0 ) {
        
        prime = false;
    
            
        }

Upvotes: 0

Related Questions