Hi guys, I have a small problem with double link list opertion. The detailed program is in below(not the full version, only the two functions with problem). These two function work well when they are compile in single cpp file. However, when I want to seperate the function in two cpp file, it will cause error and the exe window will soon exit. Can anyone figure out why? Thank you in advance :)
At a glance, this is not enough code to help us diagnose the issue. Show us a minimal but complete example of the code that doesn't run correctly.
How do you know that the crash happens on line 6?
(*Head).prev = nullptr; //this cause exe crash,
Assigning a pointer to be null does not cause a crash. Unless you already had undefined behavior before that point, and it just so happened to manifest at that point..
Edit: I do see one issue, although it wouldn't cause a crash if the data itself is correct. You change your 'head' variable up to the point where it is assigned nullptr (the last time line 29 is called). At this point, there is no way that the loop on line 34 will ever be called. You need to save the last valid node pointer, and then go in the reverse direction.
It shows that the error is 139(SIGSEGV) and I search on the internet this equates to a read or write of a memory address that's not mapped in the process. I do not see where this error come from.
As a supplement, although it shows this error, the other function such as sorting,swapping nodes work fine and the cout function can show the expected text, but the exe window still gonna close really fast.
I think if these function can be processed means that I do create and pass the correct memory address of head, and I'm curious about how this error comes.
I also saw some error is SIGHUP P1990 Term Hangup detected on controlling terminal or death of controlling process.
I do some testing and i think the error happens in this function is there some code i need to add if new operator is operated in different cpp and return address to main.cpp?
//addHead() function is in List_operation.cpp
ListNode* addHead()
{
ListNode* Head = new ListNode;
Head->data = 10 ;
Head->prev = nullptr;
Head->next = nullptr;
return Head;
}
Thank you all for your help! Problem solved. After checking, I found out that it is the memory leak problem and I need to deallocate memory if I want to compile them in separate cpp. Thanks.