Segmentation Fault (Core dumped) in c++

25,022

Solution 1

you should write:

for (int i = 0; i<4; i++) //0,1,2,3 = total 4 values
{
    cout << str[i] << "\n";
}

Solution 2

C++ Arrays are 0-based so you cannot access str[4], since its indexes range 0-3.
You allocated an array, length of 4:

string str[4]

Then your loop must terminate when:

i < 4

Rather than i < 5.

Solution 3

counter should be from zero to three. For loop needs modification.

Solution 4

str is a string[4], so it has 4 elements, which means indices 0-3 are valid. You are also accessing index 4.

Solution 5

You are getting segmentation fault because you trying to access an element which does not exists i.e. str[4] The possible indices are from 0-3.

Share:
25,022
Jatin
Author by

Jatin

SOreadytohelp

Updated on August 11, 2020

Comments

  • Jatin
    Jatin almost 4 years

    This code when executed displays the expected output but prints segmentation fault (core dumped) at the end :

    string str[4] = {
        "Home",
        "Office",
        "Table",
        "Bar"
    };
    
    for (int i = 0; i<5; i++)
    {
        cout << str[i] << "\n";
    }
    

    Output:

    Home
    Office
    Table
    Bar
    Segmentation fault (core dumped)
    

    What is the signinficance of segmentation fault (core dumped). I searched and it seems an error like that occurs when you try to access unallocated memory, so, what's wrong with the above code?