Abort trap: 6 C++

  abort, c++, c++98, dynamic-memory-allocation, file

My code works perfectly but I got an "Abort trap: 6" and I’m trying to fix it. (The following code is about to write the content of the array in a file and then open this file and read this content into an array and display the array’s content.)

I suspect that ziziMechant.dat was a bit larger than I might expect? That’s my best guess so far. How to fix this abort trap error? (and any tips to prevent it would be welcome – I’m beginner level)

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void arrayToFile(string fileName, int *array, int sizeArray)
{
    ofstream outputFile(fileName, ios::binary); // file opened in binary mode

    outputFile.write(reinterpret_cast<char *>(array), sizeArray * sizeof(int)); //.write 
member accepts pointer to char as first argument
                                                                            // so use 
reinterpret_cast when calling it

    outputFile.close();
}

void fileToArray(string fileName, int *array, int sizeArray)
{
    ifstream inputFile(fileName, ios::binary);

    inputFile.read(reinterpret_cast<char *>(array), sizeArray * sizeof(int)); //.read 
 member accepts pointer to char as first argument
                                                                          // so use 
reinterpret_cast when calling it

    inputFile.close();
 }

 int main()
{
    const int arraySize = 5;
    int array[arraySize] = {1, 2, 3, 4, 5};
    int arrayToRead[arraySize];

    //call arrayToFile function to write into file
    cout << "Let's start to write on the file from the arrayn";
    arrayToFile("ziziMechant.dat", array, sizeof(array));
    cout << "Donen";

    //call fileToArray to read from file
    cout << "Let's read that file to the arrayn";
    fileToArray("ziziMechant.dat", arrayToRead, sizeof(arrayToRead));
    cout << "Job donen";

    //display the array we just read
    cout << "Let's display the array contentn";
    for (int i = 0; i < arraySize; i++)
    {
         cout << arrayToRead[i] << ",";
    }
    cout << "n";

    return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT