[英]Segmentation Fault, when assigning member variable
For some reason I am getting a segmentation fault when I try to assign member variablesto a value stored in a struct in a vector.出于某种原因,当我尝试将成员变量分配给存储在向量结构中的值时,我遇到了分段错误。 If I comment out that assignment the segmentation fault goes away.
如果我注释掉该分配,分段错误就会消失。
Where it happens is down below and is marked with the asterisks.它发生的位置在下方并标有星号。 The rest of my code can be found on a link to my github below if that helps.
如果有帮助,可以在下面指向我的 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;
}
I found the bug.我发现了这个错误。 I was trying to get a value from an element from fragList before anything was pushed to fragList.
在将任何内容推送到 fragList 之前,我试图从 fragList 中的元素获取值。 I just used an if statement to make sure it was not empty.
我只是使用了一个 if 语句来确保它不是空的。 Sorry I'm just starting out with programming, but I really appreciate the feedback and help I get here.
抱歉,我刚刚开始编程,但我非常感谢反馈并帮助我到达这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.