C语言 指针默认值 .?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7240365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pointer default value .?
提问by Jeegar Patel
Look,
看,
typedef struct jig
{
int *a;
int *b;
}temp;
now stage 1:
现在第一阶段:
temp *b;
b= (temp*)malloc(sizeof(temp));
if(b->a != NULL)
printf("a is not null\n");
else
printf("a is null\n");
if(b->b != NULL)
printf("b is not null\n");
else
printf("b is null\n");
output is :
输出是:
a is null
b is null
now stage 2:
现在第二阶段:
temp b;
if(b.a != NULL)
printf("a is not null\n");
else
printf("a is null\n");
if(b.b != NULL)
printf("b is not null\n");
else
printf("b is null\n");
output is :
输出是:
a is not null
b is not null
why this is happening?
为什么会这样?
回答by Seth Carnegie
Pointers have no default value. The value they have is just whatever junk was in the memory they're using now. Sometimes a specific compiler will zero out memory, but that's not standard so don't count on it.)
指针没有默认值。他们拥有的价值就是他们现在使用的内存中的任何垃圾。有时特定的编译器会将内存清零,但这不是标准的,所以不要指望它。)
The memory from malloc being NULL was a coincidence; it could have been any other value just as easily. You need to and should always manually set all your pointers to NULL.
malloc 的内存为 NULL 纯属巧合;它可以很容易地成为任何其他价值。您需要并且应该始终手动将所有指针设置为 NULL。
Another alternative is you can also use calloc, which does the same thing as malloc but sets all bits to 0 in the block of memory it gives you. This doesn't help with stack variables though, so you still have to set those to NULL by yourself.
另一种选择是您也可以使用 calloc,它与 malloc 执行相同的操作,但将其提供的内存块中的所有位设置为 0。但这对堆栈变量没有帮助,因此您仍然必须自己将它们设置为 NULL。
回答by Dhaivat Pandya
This is completely operating system dependent, there's no telling where pointers will be pointing in what case, since that isn't specified. You should always set your pointers to NULL no matter what.
这完全取决于操作系统,不知道在什么情况下指针将指向哪里,因为没有指定。无论如何,您应该始终将指针设置为 NULL。
回答by cnicutar
Chance, that's what's happening. Nobody says uninitialized, non-static memory needs to hold any value. Both could contain anything.
机会,这就是正在发生的事情。没有人说未初始化的非静态内存需要保存任何值。两者都可以包含任何东西。
- In the first case it simply happened that
mallocreturned memory from an erased page (so it contains 0) - In the second case there was stuff on the stack so the memory contains garbage
- 在第一种情况下,它只是
malloc从已擦除的页面返回内存(因此它包含 0) - 在第二种情况下,堆栈上有东西,所以内存包含垃圾
回答by hamstergene
In both cases the contents of tempwill be uninitialized (random) data. They can be null, or non-null. No matter how consistently you get the same values, don't rely on that unless the documentation specifically states what they must be.
在这两种情况下, 的内容都temp将是未初始化的(随机)数据。它们可以为空或非空。无论您获得相同值的一致性如何,除非文档明确说明它们必须是什么,否则不要依赖它。

