gpt4 book ai didi

c - 为什么 malloc 在 gcc 编译器中将 o 作为默认值返回?

转载 作者:行者123 更新时间:2023-11-30 21:42:56 31 4
gpt4 key购买 nike

嗨,我在这里新学习,请解释下面的问题,我自己学习了很多天,我确实有一些带有 malloc 函数的 doout。请帮助我知道这个网站不适合初学者,但我无法找到其他方法来找到解决方案

 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?
}

谢谢老师

最佳答案

“释放”意味着“再次可供分配”。不会自动删除/覆盖内存内容,因为这会对性能产生负面影响。如果您希望将面积设置为一个值,则必须在调用 free() 之前自行完成。不过,这在发布代码中是不好的做法(除了数据安全原因之外)。

分配内存时也是如此:它不会被设置为任何特定值,但包含它之前碰巧包含的内容。如果您希望将其初始化为零,请使用calloc()。如果您想将其设置为特定的其他值,请在分配后使用 memset() 。再次强调,这会对性能产生影响,而且通常是不必要的。

至于你的最后一个问题,"%d" 用于有符号整数。对于无符号,请使用 "%u"

关于c - 为什么 malloc 在 gcc 编译器中将 o 作为默认值返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25419518/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com