分配成员变量时出现分段错误
问题描述:
出于某种原因,当我尝试向成员变量赋值存储在向量中的结构中的值时,出现了分段错误。如果我评论这个分配,分段错误就会消失。分配成员变量时出现分段错误
它发生的位置在下方,并标有星号。如果有帮助,我的代码的其余部分可以在我的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;
}
答
我发现的bug。我试图从fragList中的元素获取值,然后将任何内容推送到fragList。我只是使用了一个if语句来确保它不是空的。对不起,我刚刚开始编程,但我非常感谢我的反馈和帮助。
请编辑您的问题以提供[mcve]。 –
解决这些问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://stackoverflow.com/help/mcve)示例,该示例再现了您的问题,以及您在调试器。 –
编译你的GitHub代码时,函数'iter_swap()'没有声明。它是一个没有记录的宏吗? –