user5323078
user5323078

Reputation:

Why this error? - Segmentation fault (core dumped)

My code compiles just fine. I am running and compiling it using another server that I connect to. When I run it, I get this error that says - Segmentation fault (core dumped). It runs perfect when I compile and run it locally on my mac, just not when I use levi (the virtual machine we use to submit our files.) What do I do to not get this error message and for my code to run? Here is my code:

//
//  ChaseGraingerSection6.cpp
//
//  Created by Chase Grainger on 3/19/18.
//
// I typed all of this code on my own and did
// not copy any code from any outside sources.

#include <iostream>
#include <fstream>



int main() {

    const int my_dimension = 10; // dimension of 'my_array'
    std::string my_array[my_dimension]; // array of fixed amount of strings
    int x = 0; // used to add lines of text form 'word.txt' to 'my_array'
    int y = 0; // used when reversing array values
    int num_of_lines = 0; // keeps track of # of lines in text file[s]
    std::string text; // used when reading lines from 'word.txt'
    std::string my_reversed_array[num_of_lines]; // reversed order array

    std::ofstream outData; // output stream 'outData'
    std::ifstream inData; // input stream 'inData'

    inData.open("word.txt"); // opens input stream
    while (getline(inData, text)) { // runs through each line in 'word.txt'
        my_array[x] = text; // sets index value of array to line in text file
        num_of_lines += 1;
        x += 1;
    }
    inData.close(); // closes input stream

    // at this point, my_array has the text needed

    outData.open("chase.txt");

    for (x = num_of_lines - 1; x >= 0; x--) { // assisngs values in reverse order from one array to another
        my_reversed_array[x] = my_array[y];
        y += 1;
    }
    for (x = 0; x <= num_of_lines - 1; x++) {
        outData << my_reversed_array[x] << std::endl;
    }

    outData.close();
}

Upvotes: 1

Views: 537

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385264

int num_of_lines = 0;
std::string my_reversed_array[num_of_lines];

This is not actually valid C++, but on a compiler supporting variable-length arrays as an extension this creates an array of zero size.

Now, whichever compiler you use, this array does not later magically change size if you change num_of_lines; that ship has sailed.

So, whenever you write to my_reversed_array, you are writing to memory that does not belong to you.

You are going to need dynamic allocation (or a std::vector) so that you can create an array with runtime bounds — and don't do it until you know what those bounds are.

To answer your next question (why this didn't crash on your Mac), you just got [un]lucky. The program is not required to crash; its behaviour is undefined. It could instead have summoned a brilliant genius to answer your question on Stack Overflow. Oh… wait… ;)

Upvotes: 6

Related Questions