[英]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;
}
我發現了這個錯誤。 在將任何內容推送到 fragList 之前,我試圖從 fragList 中的元素獲取值。 我只是使用了一個 if 語句來確保它不是空的。 抱歉,我剛剛開始編程,但我非常感謝反饋並幫助我到達這里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.