--- In [email protected], Gopi Krishna Komanduri
<[EMAIL PROTECTED]> wrote:
>
> Hi,
> I have a small query ..like whenever any variable is
> declared and used in one function , then scope won't
> be there outside of that function. Then how will be
> case with pointers?
Exactly the same, see below.
> like..
>
> #include<stdio.h>
> char * fun()
> {
> char *x="Gopi"; // -->Is this initialisation correct?
> return x;
> }
> main()
> {
> char *k=new char(5);
> k=fun();
> }
> Here k got value "Gopi"; But x is declared only in
> function "fun()". Does it mean , for variables whose
> memory allocated in heap instead of stack will remain
> till the end of program?
YES!
This is a sort of errors which is particularly hard to detect, and
it's really nasty for two reasons:
1) the pointer variable "x" is declared only within "fun()"; so it may
even happen that upon returning from "fun()" to the calling function
the address it contains (namely the address of the string "Gopi") will
not be available to the caller. This provokes undefined behaviour.
2) As you already mentioned, allocating memory dynamically (need not
be on the heap; there is no such C/C++ concept as a processor stack or
a heap!) in a function requires YOU to keep track of its reference (on
many modern platforms a pointer to this memory) as long as you may
need it. And it requires YOU to release the memory when you don't need
it anymore; don't rely on the OS doing this cleanup work for you, this
assumption may not always hold true.
Regards,
Nico