Search code examples
c++filestream

Program giving different output every time I run code


I've created a program which reads numbers from a file and stores in 3 arrays and then prints it in another file. The code is as follows:

    #include <iostream>
    #include <cstdlib>
    #include <fstream>

        int main() {
            std::ifstream input("input.txt");
            input >> n;
            int* array1 = new int(n);
            int* array2 = new int(n);
            int* array3 = new int(n);
            for(int i = 0; i< n; i++){   
                input_file >> array1[i];
                input_file >> array2[i];
                input_file >> array3[i];
            }
            std::ofstream output("output.txt");
            for(int i = 0; i< n; i++){
                output << array1[i] <<"\t";
                output << array2[i]<<"\t";
                output << array3[i]<<std::endl;
            }
}

Input file looks like: 5
1 2 3
3 4 5
5 6 7
7 8 9
9 10 11

Every time I run the program, it prints the second line of the output differently, such as
1 9 10 or
1 2 10 or
1 9 3

Sometimes it prints it correctly. Any help is appreciated.


Solution

  • The problem is most likely your allocations: new int(n) allocates one integer value and initializes it to the value n.

    Since you only allocate a single integer value for your arrays, you will go out of bounds and that will in turn lead to undefined behavior which makes your whole program ill-formed an invalid.

    To allocate an "array" you need to use square-brackets as in new int[n]. Or better yet, use std::vector.