Can you please tell me why I am getting a segmentation fault error

Here is the code :

#include <iostream>
#include <fstream>
#include <chrono>

using namespace std;
using namespace std::chrono;

int main()
{
    FILE *outputFile = fopen("TheIndianMobileNumbers.txt", "a");
    const int arraySize = 1000001;

    long long int thebeginnumberorendnumber = 6000000000LL;

    for (int MegaItertion = 0; MegaItertion < 4000; MegaItertion++)
    {
        auto start = high_resolution_clock::now();

        long long int* thenumbersarray = new long long int[arraySize];

        #pragma acc parallel loop
        for (int CalculationNumberPresent = 1; CalculationNumberPresent < arraySize; CalculationNumberPresent++)
        {
            thenumbersarray[CalculationNumberPresent - 1] = thebeginnumberorendnumber + CalculationNumberPresent;
        }

        for (int TheElementWhichisBeingWritten = 0; TheElementWhichisBeingWritten < arraySize - 1; TheElementWhichisBeingWritten++)
        {
            fprintf(outputFile, "%lld\n", thenumbersarray[TheElementWhichisBeingWritten]);
        }
        delete[] thenumbersarray;

        thebeginnumberorendnumber += thenumbersarray[arraySize - 2];

        auto end = high_resolution_clock::now();
        duration<double> duration = end - start;

        cout << "---------------------------------" << endl;
        cout << "---------------------------------" << endl;
        cout << "--Massive Iteration is now done--" << endl;
        cout << "---------------------------------" << endl;
        cout << "--" << duration.count() << "Seconds-----------------" << endl;
        printf("-----------%d------------------", MegaItertion);
        cout << "-------------------------" << thebeginnumberorendnumber << "-----" << endl;
        cout << "---------------------------------" << endl;
    }

    fclose(outputFile);
    return 0;
}

I used pgc++
Can you please tell me why I am getting Segmentation fault

    delete[] thenumbersarray;
    thebeginnumberorendnumber += thenumbersarray[arraySize - 2];

You’re deleting the array and then accessing it. Flip-flop these two lines so the delete comes after.

    thebeginnumberorendnumber += thenumbersarray[arraySize - 2]; 
    delete[] thenumbersarray;
1 Like

thanks

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.