分配成员变量时出现分段错误
Segmentation Fault, when assigning member variable
由于某种原因,当我试图将成员变量分配给存储在向量结构中的值时,我得到了分段错误。如果我注释掉这个赋值,分割错误就消失了。
发生的位置在下面,用星号标记。如果有帮助的话,可以在下面的github链接上找到我的代码的其余部分。
void LinkedList::findFragments(){
//Initialize variables
currentNode = head;
prevNode = head;
int fragListSize = 0;
vector<fragment> tempVec;
bool f = false;
fragment temp;
int arr[32];
//Find all the fragment groups
//Put all the isFree flags into an array
for(int i = 0; i < 32; i++){
arr[i] = currentNode->isFree;
currentNode = currentNode->next;
}
//Find Groups of 1's which show open fragments of memory
for (int i = 0; i < 32; i++) {
if (!f && arr[i] == 1) {
f = true;
temp.begin = i;
}
if (f && arr[i] == 0) {
f = false;
temp.end = i - 1;
temp.size = temp.end - temp.begin + 1;
tempVec.push_back(temp);
}
if (f && i == 31) {
f = false;
temp.end = i;
temp.size = temp.end - temp.begin + 1;
tempVec.push_back(temp);
}
}
//Make fragList equal to tempVec
fragList = tempVec;
//Sorting the fragments by size
fragListSize = fragList.size();
for(int j = 0; j < fragListSize; j++){
for(int i = 0; i < fragListSize- j - 1; i++){
if(fragList[i].size < fragList[i + 1].size){
iter_swap(fragList.begin() + i, fragList.begin() + i + 1);
}
}
}
cout << "test 3" <<endl;
int max, min;
//Find the min and max sizes of the fragments
max =0;
for(int i = 0; i < fragListSize;i++)
{
if(fragList[i].size > fragList[max].size)
{
max = i;
}
}
min =0;
for(int i = 0; i < fragListSize;i++)
{
if(fragList[i].size < fragList[min].size)
{
min = i;
}
}
for(int i =0; i< fragListSize; i++){
cout << "Begin index: " << fragList[i].begin << " End index: "
<< fragList[i].end<< "Frag Size"<< fragList[i].size << endl;
}
//Set largest and smallest Fragment size
//********************Segmentation Fault********************
largestFragment = fragList[max].size;
smallestFragment = fragList[min].size;
//Set the position of the smallest and largest fragments
largestFragmentPos = max;
smallestFragmentPos = min;
}
GitHub项目代码
我发现了这个bug。在任何东西被推送到fragList之前,我试图从fragList的元素中获得一个值。我只是使用了if语句来确保它不是空的。很抱歉,我刚刚开始编程,但我真的很感谢你的反馈和帮助。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?