You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

malloc空间分配不足引发free()报错invalid next size (fast)求助

Fixing 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 the malloc call after you read the value of n, so you can allocate exactly the amount of memory you need:

    int *arr = malloc(n * sizeof(int));
    

    This creates an array of n integers instead of just one.

  • Check for malloc failure
    Memory allocation isn't guaranteed to succeed, so always add a check to make sure arr isn't NULL:

    if (arr == NULL) {
        fprintf(stderr, "Memory allocation failed!\n");
        return 1;
    }
    
  • Validate input (optional but recommended)
    Add checks to ensure scanf actually 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:47:26