[英]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
以字節為單位分配空間,並且一個整數大於1個字節寬,因此
buffer = (int*)malloc(n+1);
應該
buffer = malloc((n+1) * sizeof(int));
您應該為n + 1
整數分配空間。 因此,您必須將其乘以類型的大小。
一種更清潔,更可維護的方式是
buffer = malloc((n + 1) * sizeof(*buffer));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.