求助:使用scanf输入整数后C程序崩溃问题
Hey there! Let's dig into why your polynomial program is crashing after inputting integers. First, let's start with the code snippet you shared, then walk through the most likely culprits for this kind of crash.
Your Shared Code Snippet
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "Homework.h" #include "Fraction.h" int main() { //Input from user int degree, i; printf("Insert the degree of the polynomial: \n"); scanf("%d", °ree); //Get t... }
Common Causes for the Crash
Since your code cuts off right after getting the degree, here are the most frequent issues that lead to crashes in polynomial implementations like this:
Incorrect Dynamic Memory Allocation
If your polynomial uses a dynamic array (e.g.,Fraction* coefficients = malloc(sizeof(Fraction) * (degree + 1))) to store coefficients, there are two easy mistakes here:- You forgot that a degree-
npolynomial hasn+1coefficients (from the constant term up tox^n). Using justdegreeinstead ofdegree+1will leave you short on memory, causing out-of-bounds access. - You didn't check if
mallocfailed. If memory allocation returnsNULL, trying to write to that pointer will immediately crash your program. Always add a check:Fraction* coeffs = malloc(sizeof(Fraction) * (degree + 1)); if (coeffs == NULL) { fprintf(stderr, "Failed to allocate memory!\n"); return 1; }
- You forgot that a degree-
Unvalidated Input
If the user enters something that's not an integer (like a string or decimal),scanfwill fail to updatedegree, leaving it with a garbage value. Using this garbage value to allocate memory or run loops will lead to unpredictable behavior (and crashes). Add input validation:if (scanf("%d", °ree) != 1 || degree < 0) { fprintf(stderr, "Please enter a non-negative integer for the degree!\n"); return 1; }Issues with the
FractionType
If yourFractionstruct has uninitialized members, or if you're performing operations (like assignment, copying, or destruction) that have memory bugs (e.g., double-freeing pointers insideFraction), this could cause crashes when you start creating or assigning coefficients for your polynomial.Loop Boundary Errors
When you loop to input coefficients, make sure your loop runs exactlydegree + 1times. A loop likefor (i = 0; i < degree; i++)will miss the constant term, while an overextended loop will go out of bounds and crash the program.
Next Steps
To pinpoint the exact issue, could you share:
- The rest of the
mainfunction (especially where you input coefficients and interact with the polynomial) - The definition of your polynomial struct from
Homework.h - Any functions related to creating, initializing, or destroying polynomials
内容的提问来源于stack exchange,提问作者Matteo Pagin

