c - 错误 : free(): invalid next size (fast)

标签 c memory memory-management malloc undefined-behavior

代码如下:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = malloc(sizeof(int));
    int n;
    printf("input number:\t");
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
    }
    for(int i = 0; i < n; i++) {
            printf("%d", arr[i]);
    }
    free(arr);

    return 0;
}

它一直运行到 scanf 然后就崩溃了:

1234875770417Aborted (core dumped)

我看过其他类似的帖子,但没有一个能解决我的问题。

最佳答案

此声明中的初始化程序

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

仅为 int 类型的一个对象分配内存。所以在这种情况下,n 可能不会大于 1。

你至少应该写

int main( void ) {
    int n;
    printf("input number:\t");
    scanf("%d", &n);
    int *arr = malloc( n * sizeof(int));
    //...

此外,最好将变量 n 声明为 unsigned int 类型而不是 int 类型。

请注意,根据 C 标准,不带参数的函数 main 应声明如下

int main( void )

这是一个更新的程序。

#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
    unsigned int n = 0;

    printf( "input a non-negative number:\t" );
    scanf( "%u", &n );

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

    for ( unsigned int i = 0; i < n; i++ ) 
    {
        scanf( "%d", &arr[i] );
    }

    for ( unsigned int i = 0; i < n; i++ ) 
    {
        printf( "%d ", arr[i] );
    }
    putchar( '\n' );

    free( arr );

    return 0;
}

它的输出可能看起来像

input a non-negative number:    10
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9

关于c - 错误 : free(): invalid next size (fast),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49708766/

相关文章:

c++ - 关于循环变量优化的标准合规行为是什么?

linux - Linux 中进程间如何共享代码段?

c++ - 增加 C++ 程序 CPU 使用

algorithm - 如何管理 Buddy 算法中的 header block ?

c - 在循环内或循环外声明变量,有很大区别吗?

python - 使用 cmake 构建 Python 共享对象绑定(bind),这取决于外部库

c - 如何使用指针从数组中删除字段?

android - Dealing with Large Bitmaps(平铺小位图来创建墙纸)

memory-management - 如果 malloc 可以失败,为什么堆栈变量初始化不能(至少我们不检查)?

c - C 中的行很奇怪