Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char pointer declaration inside and outside main()

Tags:

c++

c

pointers

The program that I wrote is :

char* str_1;
void main()
{
    char* str_2;
    printf("STR_1 Address of pointer : %p\n", &str_1);
    printf("STR_2 Address of pointer : %p\n", &str_2);
    printf("STR_1 pointer : %p\n", str_1);
    printf("STR_2 pointer : %p\n", str_2);
}

And the output is the following :

STR_1 Address of pointer : 00404048
STR_2 Address of pointer : 0028FF1C
STR_1 pointer : 00000000
STR_2 pointer : 7EFDE000

How can we explain this ?

like image 419
JohnnyCat Avatar asked Jan 28 '26 02:01

JohnnyCat


1 Answers

Variables defined at namespace scope are value-initialized by default, that's why str_1 points to NULL.

str_2 is not initialized, so the line

printf("STR_2 pointer : %p\n", str_2);

is actually undefined behavior. A garbage value is printed.

like image 154
Luchian Grigore Avatar answered Jan 29 '26 14:01

Luchian Grigore