基于链表的多项式乘法程序段错误问题排查及scanf是否会引发段错误的疑问
Hey there! Let's break down your segmentation fault issue and address your scanf concern step by step.
First, let's clear up your scanf question: No, your current scanf statements aren't causing the segmentation fault. The scanf("%d%d",&co1,&po1); line uses valid addresses for your integer variables (co1 and po1 are properly declared in main), so scanf itself won't trigger a crash here. The issue lies elsewhere in your code.
The Critical Bug Causing Segmentation Faults
Looking at your addterms function, there's a major flaw in the code that adds new terms to the result list when there's no matching power:
if(flag==0) { cur=res; while(cur!=NULL) { cur=cur->add; } cur->add=temp; // Crash happens here! }
When this code runs, the loop continues until cur becomes NULL (after reaching the end of the list). Trying to access cur->add when cur is NULL is a classic null pointer dereference, which directly triggers a segmentation fault.
To fix this, change the loop condition to stop at the last valid node (instead of going past it):
if(flag==0) { cur=res; while(cur->add != NULL) // Stop at the last node with a non-null next pointer { cur=cur->add; } cur->add=temp; // Now cur points to the last valid node, safe to modify its add }
This bug will trigger when your multiply function tries to add a new unique power term, which explains why you're seeing crashes during polynomial operations.
Addressing Your Immediate Crash During Input
You mentioned the crash happens when entering the last term of the second polynomial. While your insert function looks correct, there's a possibility that:
- The crash is actually happening later in the
displayormultiplysteps, but buffered output makes it seem like it's happening during input (since yourprintf("Insert");doesn't include a newline, so the message might not flush to the console before the crash). - A leftover core dump from a previous run is confusing your test results.
After fixing the addterms bug, recompile and test your program again. This should resolve the segmentation fault issues you're seeing.
Additional Minor Improvements
- Add newlines to your
printfstatements (e.g.,printf("Enter the number of polynomial terms\n");) to make input/output cleaner and avoid buffered output confusion. - In the
addtermsfunction, once you find a matching power, you can break out of the loop early to save some computation:while(cur!=NULL) { if(cur->po==po) { cur->co=cur->co+co; flag=1; break; // No need to check further terms } cur=cur->add; }
备注:内容来源于stack exchange,提问作者Hammish Raj Wadeyar

