调用L.deleteEle()后执行L.insert()触发SIGSEGV段错误求助
deleteEle() Then insert() in Custom C++ List Class Let's break down exactly what's causing your segfault and how to fix it, step by step.
Root Cause: Using malloc() for C++ Objects with Non-POD Members
Your node struct contains a std::string member, which is a non-POD (Plain Old Data) C++ object. When you use malloc() to allocate memory for a node:
nPtr = (nodePtr)malloc(sizeof(node));
malloc() only allocates raw memory—it does not call the constructor for std::string. This leaves the data member in an uninitialized, invalid state. When you try to assign to it later with nPtr->data = element;, the std::string's assignment operator tries to operate on garbage internal state (like a pointer to random memory), which triggers the segmentation fault.
Why did this work before calling deleteEle()? That's just the nature of undefined behavior—sometimes bad code appears to work by accident. The deleteEle() operation likely altered memory layout or triggered some implicit check that made the hidden error surface.
Fixes to Resolve the Issue
Replace
malloc()/free()withnew/delete
C++ requires usingnewto create objects (it allocates memory and runs constructors) anddeleteto destroy them (runs destructors and frees memory).- In
insert(), replace themallocline with:nPtr = new node; - In every spot in
deleteEle()where you callfree(cPtr), replace it with:delete cPtr;
This ensures your
std::stringmembers are properly constructed and destructed, eliminating the invalid state that caused the segfault.- In
Fix Edge Case in
deleteEle()When Removing the Last Element
When you delete the final node, your current code setstail = pPtr, but ifcountdrops to 0,pPtrwill beNULL(since you were at the last element), and you still need to setheadtoNULLto avoid invalid pointers later. Update that branch:if(position==count){ tail = pPtr; delete cPtr; count -= 1; if (count == 0) { head = NULL; tail = NULL; } else { tail->next = NULL; } return true; }Add the Missing
size()Member Function
Yourmain()callsL.size(), but yourListclass doesn't have this method—this would cause a compile error before even hitting the segfault. Add this to your class public section:int size() const { return count; }
Why These Changes Work
newanddeletehandle the lifecycle ofstd::stringcorrectly, ensuring no uninitialized object states.- Fixing the last-element deletion edge case prevents dangling pointers to deallocated memory.
- Adding
size()resolves the compile error so your code can run as intended.
内容的提问来源于stack exchange,提问作者1337r0b07

