在我的程序中,calloc()
不能超过38个大小,但是如果小于这个数字,它就能完美运行。在这种情况下,我想分配128 int
,然后将其释放。
怎么了?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int *a;
int *x;
x = malloc(512 / sizeof(int));
a = x;
int n = (512 / sizeof(int));
int i;
for (i = 0; i < n; i++)
{
printf("Address of x[%d] = %x\n", i, x );
printf("Value of x[%d] = %d\n", i, *x );
x++;
}
free(a);
int *y = (int *)malloc(512 / sizeof(int));
a = y;
for (i = 0; i < n; i++)
{
printf("Address of y[%d] = %x\n", i, y );
printf("Value of y[%d] = %d\n", i, *y );
y++;
*y = i + 1;
}
free(a);
int *z = (int *)calloc(38, sizeof(int));
a = z;
for (i = 0; i < 38; i++)
{
printf("Address of z[%d] = %x\n", i, z );
printf("Value of z[%d] = %d\n", i, *z );
z++;
}
free(a);
return 0;
}
答案 0 :(得分:3)
首先问题是,您没有初始化x
或y
的值,但仍尝试打印它们,而另一个问题则更为重要:
n = 512/sizeof(int)
然后你是malloc
x = malloc(512/sizeof(int))
你应malloc
这样
x = malloc(n*sizeof(int))
产生
x = malloc(512)
但是因为你想分配128 of int
,所以做得更清楚
n = 128;
x = malloc(n * sizeof(int));
这是固定代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int *a;
int *x;
x = malloc (512);
a = x;
int n = (512/sizeof(int));
int i;
for (i = 0; i < n; i++)
{
*x = i; /* intialize the value of x[i] */
printf("Address of x[%d] = %p\n", i, x );
printf("Value of x[%d] = %d\n", i, *x );
x++;
}
free(a);
int *y = malloc(512);
a = y;
for (i = 0; i < n; i++)
{
*y = i+1; /* initialize the value of y[i] */
printf("Address of y[%d] = %p\n", i, y );
printf("Value of y[%d] = %d\n", i, *y );
/* *y = i+1; move this before the printf */
y++;
}
free(a);
int *z = calloc(38, sizeof(int));
a = z;
for (i = 0; i < 38; i++)
{
printf("Address of z[%d] = %p\n", i, z );
printf("Value of z[%d] = %d\n", i, *z );
z++;
}
free(a);
return 0;
}
您必须始终检查malloc
失败后返回NULL
的结果。如果它确实返回NULL
并且你没有检查,你会取消引用NULL
指针,这不是一个好主意。
具有讽刺意味的是,代码中唯一真正正确的部分是calloc
部分,除了不检查返回的值。