這是我發佈的第一個問題,我確保檢查其他線程的主題標題和問題相同,但是迄今爲止,沒有任何解決方案對我有幫助。Seg Fault只發生在每次運行
問題:當經由一個生成文件彙編包括以下
OBJ = hw1.o
hw1: $(OBJ)
g++ -g -o hw1 $(OBJ)
hw1.o:
./PHONE:
clean
clean:
rm hw1.o
我接收有關每3個運行段故障。我在這個網站上看到的解決方案包括在主程序之外移動linked_list*
對象,但是當我嘗試這個時,它在每次運行中給我提供了分段錯誤。
下面是我的代碼:
#include<iostream>
#include<iomanip>
#include<fstream>
#include<vector>
struct linked_list
{
int data;
void set_data(int d) { data = d; }
int get_data(void) {return this->data; }
void set_next(linked_list* ll) { this->next = ll; }
linked_list* get_next(void) { return this->next; }
linked_list* next;
};
//linked_list* head; this is where I moved the objects out of main
//linked_list* tail; which cause seg faults every run
//linked_list* temp;
void print_linked_list(linked_list*, int);
int main()
{
linked_list* head;
linked_list* tail;
linked_list* temp;
std::ifstream data1, data2;
int element = 0; //elements from list
int size_ll = 0;
//Open data1.txt and check for errors
//data1.txt contains elements to be added in to both data structures
data1.open("data1.txt");
if(data1.fail())
{
std::cout << "Error: Couldn't open data1.txt\nCheck that file exists...\n";
return 0;
}
//Open data2.txt and check for errors
//data2.txt contains elements which need to be deleted in both data structures
data2.open("data2.txt");
if(data2.fail())
{
std::cout << "Error Couldn't open data2.txt\nCheck that file exists...\n";
return 0;
}
head->set_next(NULL);
tail->set_next(NULL);
for(int i = 0; i <= 150; i ++)
{
data1 >> element;
temp = new linked_list;
temp->set_data(element);
temp->set_next(NULL);
if((size_ll % 50) == 0 && size_ll != 0)
{
std::cout << "\n\nPrinting current linked list (left to right, top to bottom):";
std::cout << "\nCurrent size: " << size_ll;
std::cout << "\n\n";
print_linked_list(head, 0);
std::cout << "\n";
std::cout << "End of current list.\n";
}
//handling linked list
if(size_ll == 0)
{
head = tail = temp;
size_ll++;
}
else
{
tail->set_next(temp);
tail = temp;
size_ll++;
}
}
data1.close();
data2.close();
}
//pass the next element of the linked list
void print_linked_list(linked_list* current, int lol)
{
if(current == NULL)
{
return;
}
std::cout << std::setw(4) << current->get_data() << " ";
if(lol == 9)
{
std::cout << std::endl;
lol = -1;
}
print_linked_list(current->get_next(), lol+1);
}
你試過在調試器下運行這個嗎?什麼路線是違約的? –
當我使用GDB調試器時,它永遠不會給我一個seg故障,因此很難追蹤 – Sc00by
核心轉儲,然後呢? –