Re: [Dev-C++] A problem about the pointer.
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Paul I. <pi...@ot...> - 2004-06-15 19:23:40
|
Quoting Bruce jjs <per...@ya...>:
> I have write a very simple program to test the pointer.The progr=
am is
> list belove:
> /* **************************************** */
> #include <stdio.h>
> =20
> int *p;
> =20
> =20
> void Func(void)
> {
> int number;
> =20
> number =3D 11;
> p =3D &number;
> }
> =20
> main()
> {
> Func();
> printf("*p =3D %d\n", *p);
> }
> /* ***************************** */
> The result is :
> *p =3D 11
> The variable "number" is local variable that will be destoryed af=
ter
> leave the Func( ) and the pointer "p" is pointer to it.Although p is gl=
obal
> variable,it pointer to a deleted area. To my way of thinking,*p should =
be a
> ignorance value.Is my understand wrong?
> Thanks,
> Bruce.J
>=20
What do you mean by "*p should be a ignorance value"?
This is what the compiler makes out of Func():
__Z4Funcv:
LFB1:
pushl %ebp ; Stores ebp on the stack
LCFI0:
movl %esp, %ebp ; copies the stack pointer (esp) to ebp
LCFI1:
subl $4, %esp ; esp =3D esp - 4 : This makes room for the=20
; 'number' variable on the stack (since the stack
; is growing towards lower addresses, 'number' won't
; be overwritten when pushing further data on the stack)
LCFI2:
movl $11, -4(%ebp) ; the 'number' variable is initialized to 11
; intel syntax is probably clearer: mov [DWORD PTR ebp - 4], 11
; (move the value 11 to the address pointed to by
; (ebp + 4) )
; (automatic variables are always accessed via ebp, which=20
; is the reason it is initialized to esp at the beginning of=20
; the function. (esp may change during the execution of=20
; the function body)
leal -4(%ebp), %eax ; lea : load effective address
; this intruction loads the address of the 'number' variable
; to register eax. (as can be seen, 'number' hasn't moved...)
movl %eax, _p ; the address of 'number' is stored in the variable p
; (renamed to _p by the compiler). p is actually an address:
; .bss
; .align 4
; _p:
; .space 4
; meaning that 4 bytes of space is reserved "in the .bss section"
leave ; performs cleanup:
; esp=3Debp, pop ebp=20
; this restores the stack pointer (to the point when it was=20
; stored in ebp) and then ebp is restored.
ret ; return from function
As can be seen, no area is "deleted". Nor is anything cleared (that would=
cost
time). Next time a function is called, the memory area that p points to i=
s
likely to change. As in this case:
#include <stdio.h>
=20
int *p;
=20
=20
void Func(void)
{
int number;
=20
number =3D 11;
p =3D &number;
}
void Func2(void)
{
int a;
=09
a=3D 5;
} =20
=20
main()
{
Func();
printf("*p =3D %d\n", *p);
Func2();
printf("*p =3D %d\n", *p);
=20
}
When Func2 is called the variable 'a' will be assigned the same address t=
hat
'number' occupied...
Hope this helps ;-)
|