Linux C ++中的分段错误(核心转储)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11176820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Segmentation Fault (Core dumped) in c++
提问by Jatin
This code when executed displays the expected output but prints segmentation fault (core dumped)
at the end :
此代码在执行时显示预期的输出,但segmentation fault (core dumped)
在最后打印:
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?
分段错误(核心转储)的意义是什么。我搜索了一下,当您尝试访问未分配的内存时,似乎会发生类似的错误,那么,上面的代码有什么问题?
采纳答案by Roee Gavirel
you should write:
你应该写:
for (int i = 0; i<4; i++) //0,1,2,3 = total 4 values
{
cout << str[i] << "\n";
}
回答by Tariq Mehmood
counter should be from zero to three. For loop needs modification.
计数器应该从零到三。For 循环需要修改。
回答by mathematician1975
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
您正在访问数组末尾之后的数据。str
是一个大小为 4 的数组,但您正在访问循环中的第五个元素,这就是您收到段错误的原因
回答by Kevin
str
is a string[4]
, so it has 4 elements, which means indices 0-3 are valid. You are also accessing index 4.
str
是 a string[4]
,所以它有 4 个元素,这意味着索引 0-3 是有效的。您也在访问索引 4。
回答by Nadir Sampaoli
C++ Arrays are 0-based so you cannot access str[4], since its indexes range 0-3.
You allocated an array, length of 4:
C++ 数组是基于 0 的,因此您不能访问 str[4],因为它的索引范围是 0-3。
您分配了一个数组,长度为 4:
string str[4]
Then your loop must terminate when:
那么你的循环必须在以下情况下终止:
i < 4
Rather than i < 5
.
而不是i < 5
。
回答by Srijan
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.
您遇到分段错误,因为您试图访问不存在的元素,即str[4]
可能的索引为 0-3。