Jatin
Jatin

Reputation: 14269

Segmentation Fault (Core dumped) in c++

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?

Upvotes: 2

Views: 25559

Answers (6)

Srijan
Srijan

Reputation: 1284

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.

Upvotes: 2

Nadir Sampaoli
Nadir Sampaoli

Reputation: 5555

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.

Upvotes: 5

Kevin
Kevin

Reputation: 56049

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

Upvotes: 3

mathematician1975
mathematician1975

Reputation: 21351

You are accessing data past the end of your array. str is an array of size 4, but you are accessing a fifth element in your loop, that is why you get a seg fault

Upvotes: 1

Tariq Mehmood
Tariq Mehmood

Reputation: 269

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

Upvotes: 3

Roee Gavirel
Roee Gavirel

Reputation: 19445

you should write:

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

Upvotes: 9

Related Questions