当我编写以下代码时,我得到了奇怪的答案。
#include<stdio.h>
#include<stdlib.h>
main()
{
int *p=malloc(1);
if(p==0)
printf("memory not assigned\n");
else
{
printf("memory assigned\n");
printf("enter an int\t");
scanf("%d",p);
printf("\n You entered number %d",*p);
printf("\nIt has been stored at-%p",p);
}
}
我认为 malloc 将参数作为字节数。所以在这里我输入了 1 个字节,我知道在我的机器上 int 需要 4 个字节进行存储(通过 sizeof() )但代码仍然没有显示错误,我可以输入一个 int 值。即使我输入 3333333 它也不会抱怨。如果我使用 malloc() 而不是 malloc(1) gcc 抱怨 malloc 的参数太少但仍然给出相同的结果。我无法理解这种行为。有人请澄清一下。
我通过虚拟盒在 gcc 上运行它。