On Thu, 2004-03-04 at 15:38, Vikas Upadhyay wrote:
> From: "Abhijit Menon-Sen" <[EMAIL PROTECTED]>
> 
> > At 2004-03-04 12:24:25 +0530, [EMAIL PROTECTED] wrote:
> > >
> > > According to me, as we have "string" as local variable, it should
> vanish.
> > > But, i am still able to return and print the string "hello world".
> >
> > Returning a pointer to local variables is undefined; that is, there is
> > no guarantee whatsoever about its behaviour. In particular, it doesn't
> > need to "vanish" (but it may).
>     By vanish I mean, function gone it's data gone. Each function data
> (unless got through malloc or defined static) is put on it's     stack
> frame, so when function returns the stack frame is popped out. So local
> variable no more exists !!!

Very true when the function returns the stack is emptied and all local
variables are deleted. But the pointer is made on the heap not the
stack!So you will have to "delete" the pointer manually. You are taking
control away from the compiler and telling it that you are implementing
it manually by making a pointer. So if there was a "Garbage Collector"
this is what it would collect. Otherwise like in this case you have a
memory leak.

> > So your code works only by accident. I'm surprised that gcc's warnings
> > are defeated by your intermediate assignment (ptr = string), but only
> > a little.
> >
>     This has been my understading, but now the problem is - "if all what i
> know is correct, yaar yeh kaam kyon kar raha hae".
>     I have tried it so many times ... but if it's just coincidence, what a
> beautiful coincidence    :-)

As far as gcc warning for ptr=string goes it is not complaining since
string is an array and "string" actually contains the "memory address"
of starting of the array. So since you are assigning address "string" to
ptr it is not complaining and happily proceeding.

Try adding these two statements and changing your foo() function

char * foo()
{
        char string[200];
        char * ptr=NULL;
        strcpy(string,"hello world");
        printf("StrAddr=%x\n",&string[0]); // Print address of the
starting                                  //  of the string
        ptr=string;
        printf("PtrAddr=%x\n",ptr);  //Print the address of the ptr
                                     //not the contents
}

As you will see the above two values are equal. 

Regards,

-- 
Arindam Dey

The mind is not a vessel to be 
filled but a fire to be kindled.

GPG FPR: B8E3 219E F129 F970 F4A7  BC50 9636 504A BEDF 5739


_______________________________________________
ilugd mailinglist -- [EMAIL PROTECTED]
http://frodo.hserus.net/mailman/listinfo/ilugd
Archives at: http://news.gmane.org/gmane.user-groups.linux.delhi 
http://www.mail-archive.com/[EMAIL PROTECTED]/

Reply via email to