Um ponteiro C não definido não é nulo
Estou brincando com ponteiros C. Quando eu compilar e executar o seguinte código.
Exemplo 1:
#include <stdio.h>
int main()
{
int k;
int *ptr;
k = 555;
if (ptr == NULL) {
printf("ptr is NULL\n");
} else {
printf("ptr is not NULL\n");
printf("ptr value is %d\n", *ptr);
}
printf("ptr address is %p\n", ptr);
}
Eu recebo a saída:
ptr is not NULL
ptr value is 1
ptr address is 0x7fff801ace30
Se eu não atribuir um valor a k:
Exemplo 2:
#include <stdio.h>
int main()
{
int k;
int *ptr;
if (ptr == NULL) {
printf("ptr is NULL\n");
} else {
printf("ptr is not NULL\n");
printf("ptr value is %d\n", *ptr);
}
printf("ptr address is %p\n", ptr);
}
Então a saída é como eu esperava:
ptr is NULL
ptr address is (nil)
Da mesma forma, se eu definir as variáveis fora da função:
Exemplo 3:
#include <stdio.h>
int k;
int *ptr;
int main()
{
k = 555;
if (ptr == NULL) {
printf("ptr is NULL\n");
} else {
printf("ptr is not NULL\n");
printf("ptr value is %d\n", *ptr);
}
printf("ptr address is %p\n", ptr);
}
Resultado:
ptr is NULL
ptr address is (nil)
No primeiro exemplo, onde ptr tem um endereço e um valor, esse comportamento é esperado? Se sim, então:
Por que ptr tem um endereço e valor?De onde eles vêm, o que os define?Como defino corretamente ponteiros nulos no escopo local e os mantenho nulos até que eu esteja pronto para usar?Estou compilando com o gcc no Ubuntu 12.04.04 em x64:
root@dev:~# gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.6/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.6.3-1ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.6/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.6 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.6 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
EDITAR
Eu enumerei meus exemplos acima para maior clareza.
Com base na resposta de Dietrich, pesquisei um pouco e encontrei esta pergunta:Por que as variáveis globais sempre são inicializadas em '0', mas não as variáveis locais?.