程序崩溃 malloc/free,C

Program crashes malloc/free, C

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

int tablou(n)
{
    int *buffer, i=0;
    buffer=(int*)malloc(n+1);
    if (buffer==NULL) exit(1);
    for(i=0; i<=n; i++){
        buffer[i]=i;
    printf ("%d ", buffer[i]);
    }
    //free(buffer);
    //printf("%d ", n);
    return 0;
}
int main()
{
    int n;
    printf("nr of elements:\n");
    scanf("%d", &n);
    tablou(n);
    printf("Hello world!\n");
    return 0;
}

它在第 14 行崩溃:

free(buffer);

如果我不释放内存,程序会在打印 Hello world 后出错! 如果我释放内存,它会在此之前给出错误。

由于malloc以字节为单位分配space,并且一个整数大于1字节宽,因此

buffer = (int*)malloc(n+1);

应该是

buffer = malloc((n+1) * sizeof(int));

您应该为 n + 1 个整数分配 space。所以你必须将它乘以类型的大小。

一种更简洁、更易于维护的方法是

buffer = malloc((n + 1) * sizeof(*buffer));