As a beginner I have learned that only variable definition is allotted a memory in C. But for the following program the output is 0x7ffd12792034
#include<stdio.h>
int main(char args[], int vargs)
{
int max;
printf("%p\n", &max);
}
A local variable is likely to sit on the call stack (but sometimes the compiler would optimize to put it only in some processor register or even forget it entirely). Your int max;
is a local variable definition. Its initial value is indeterminate, which practically means that it holds whatever was in the memory location (or the register) before.
Your program is printing the address of that local variable, which is on the call stack.
Because of ASLR the actual value of that address might change (or not) from one program execution to the next. It is implementation specific.
BTW, you should enable all warnings and debug information when you compile. If you use GCC, you should compile with gcc -Wall -Wextra -g
. You would then have some warnings at least, in particular because your main
function has the wrong signature. It should be int main(int argc, char**argv)
and the runtime environment guarantee that argc
is at least 1 and that the argv
array is NULL
terminated, with argc
arguments which are non-NULL
unaliased strings.
Beware of undefined behavior.
You've actually defined a variable in this case, not declared one.
If you had used the extern
keyword, you would have a declaration. But because you didn't, you have a definition.
An initializer such as int max = 1;
is not necessary to have a definition. The value will be unspecified until it is assigned one later, but it's still a definition.
If you declared the variable at file scope without an initializer, you would have a tentative definition. You could then have a full definition with an initializer later, but it would have to match the type of the tentative definition.
extern
by default. Those are easy to distinguish because they end with a ;
while a function definition has a body. For a variable you should specify extern
for a declaration.
You are printing an address in your memory which is occupied for int max
and ready to get initialize. By typing int max
you already have the place where the variable will be stored if you give it a value.
int max;
is a variable definition.int main(char args[], int vargs)
-->int main(int argc, char *args[])
orint main(void)
declarations
anddefinitions
. But the line you have there is definitely a definition, so it does allocate space. As a rough rule of thumb, it's a declaration if it includes theextern
keyword, otherwise it's a definition. (This rule isn't perfect, but it's a start.)