基于数组实现单链表的C++代码在Code::Blocks中运行崩溃,求排查
Hey there, let's figure out why your linked list code is crashing in Code::Blocks. I've spotted a couple of key issues that are causing the runtime crash—let's break them down one by one:
Key Issues Causing the Crash
Uninitialized
listptrmember
TheListclass has aNode* listptrmember, but you didn't add a default constructor to initialize it toNULL(ornullptrfor modern C++). When you createList l1inmain,listptrgets a random garbage value instead ofNULL. So in thecreatefunction, the checkif(listptr==NULL)fails, and you end up trying to accesstemp->nextwhentempis also uninitialized—this is a dangling pointer access that directly causes the crash.Minor typo in output formatting
You wrotecout << "/nEnter the data" << endl;—that's/ninstead of\n, which just prints "/n" instead of a new line. It doesn't cause the crash, but it's a small UI issue.Non-standard
mainfunction
Yourmain()should beint main()and return0at the end to comply with C++ standards. While some compilers allow the shorthand, fixing this avoids potential unexpected behavior.
Fixed Code
#include<iostream> using namespace std; class Node { int data; Node *next; public: Node(int n) { data = n; next = NULL; } friend class List; }; class List { Node *listptr; public: // Default constructor to initialize listptr to NULL List() : listptr(NULL) {} void create(); void display(); }; void List::create() { Node *temp = NULL; // Initialize temp to avoid garbage values int n, num; cout << "Enter number of nodes:" << endl; cin >> n; cout << "\nEnter the data" << endl; // Fixed /n to \n for(int i=0; i<n; i++) { cin >> num; Node *new_node = new Node(num); if(listptr == NULL) listptr = temp = new_node; else { temp->next = new_node; temp = temp->next; } } } void List::display() { Node *temp = listptr; while(temp != NULL) { cout << temp->data << "->"; temp = temp->next; } cout << "NULL" << endl; // Added to mark the end of the list } int main() { // Standard int main() List l1; l1.create(); l1.display(); return 0; // Return 0 as per C++ standards }
Breakdown of Fixes
- Added a default constructor for
Listthat initializeslistptrtoNULLusing an initializer list—this ensures the pointer starts as a valid null value instead of garbage. - Initialized
temptoNULLin thecreatefunction to avoid accidental use of an uninitialized pointer. - Fixed the
/ntypo to\nfor proper line breaks in output. - Updated
main()to follow standard C++ syntax withint main()andreturn 0;. - Added
cout << "NULL" << endl;indisplay()to clearly show the end of the linked list, making output more readable.
内容的提问来源于stack exchange,提问作者Rajan Pandey

