malloc空间分配不足引发free()报错invalid next size (fast)求助
free(): invalid next size (fast) Error in Your C Code Hey there, let's break down why your code is crashing and how to fix it. That error message is a classic sign of heap memory corruption caused by writing outside the bounds of the memory you allocated.
The Root Problem
Look at this line in your code:
int *arr = malloc(sizeof(int));
Here, you're only allocating enough space for a single integer. But then you proceed to read n integers into arr using a loop. If n is greater than 1 (which it almost certainly is in your test case), you're writing to memory that doesn't belong to your array. This overwrites the internal metadata that malloc and free use to manage the heap, leading to the free(): invalid next size (fast) error when you try to release the memory.
Step-by-Step Fixes
Allocate memory after knowing
n
Move themalloccall after you read the value ofn, so you can allocate exactly the amount of memory you need:int *arr = malloc(n * sizeof(int));This creates an array of
nintegers instead of just one.Check for
mallocfailure
Memory allocation isn't guaranteed to succeed, so always add a check to make surearrisn'tNULL:if (arr == NULL) { fprintf(stderr, "Memory allocation failed!\n"); return 1; }Validate input (optional but recommended)
Add checks to ensurescanfactually reads the values you expect—this prevents weird behavior if the user enters non-integer input:if (scanf("%d", &n) != 1) { fprintf(stderr, "Invalid input for number of elements!\n"); return 1; }
Fixed Full Code
Here's the revised code with all these fixes:
#include <stdio.h> #include <stdlib.h> int main() { int n; printf("input number:\t"); // Validate input for n if (scanf("%d", &n) != 1) { fprintf(stderr, "Invalid input! Please enter an integer.\n"); return 1; } // Allocate memory for n integers int *arr = malloc(n * sizeof(int)); if (arr == NULL) { fprintf(stderr, "Failed to allocate memory. Exiting.\n"); return 1; } // Read n integers with input validation for(int i = 0; i < n; i++) { if (scanf("%d", &arr[i]) != 1) { fprintf(stderr, "Invalid number! Exiting.\n"); free(arr); // Clean up allocated memory before exiting return 1; } } // Print the array with spacing for readability printf("Your array: "); for(int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); free(arr); return 0; }
Why This Works
By allocating exactly n * sizeof(int) bytes, you ensure you have enough space for all the integers you're reading. No more writing outside the array bounds, which means the heap metadata stays intact, and free() can do its job without throwing errors.
内容的提问来源于stack exchange,提问作者armin84

