为什么malloc在gcc编译器中默认返回o?

时间:2014-08-21 06:24:25

标签: c pointers malloc

嗨,我在这里学习,请解释下面的问题我自己学习很多天我确实有一些关于malloc功能的dout。请帮助我知道这个网站它不适合初学者但是我无法获得替代方法找到解决方案

 1) p=malloc(0) // what  will it return ?when i calculate size using sideof operator   it    throw 4 byte?

2) int *p=malloc(4) // when i scan string it throw 0 why sir?

3)  *p=2   // while p is store in heap
   scanf("%d",*p)//why *p is not possible to scanf here *p why p only?

  4) int *p=(int*)malloc(20*sizeof(int))
  for(i=0;i<5;i++)
p[i]=i+1;
free(p);
//now after free i am still get same previos value.. why not garbage coz malloc default value is garbage?

5)   int main()
{
 int *p;
 p=(int*)malloc(4);
 printf("%d\n",*p); // even here i am getting 0 why nt garbage?
 }

谢谢先生

1 个答案:

答案 0 :(得分:2)

“Freeing”意味着“再次提供分配”。没有自动删除/覆盖内存内容,因为它会对性能产生负面影响。如果您希望将区域设置为值,则必须在调用free()之前自行完成。然而,这在发布代码中是不好的做法(除了数据安全性原因之外的其他任何事情)。

分配内存时也是如此:它没有设置为任何特定值,但包含之前包含的内容。如果要将其初始化为零,请使用calloc()。如果要将其设置为特定的其他值,请在分配后使用memset()。同样,请考虑这对性能有影响,通常不是必需的。

关于您的上一个问题,"%d"适用于签名整数。对于未签名,请使用"%u"