Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

4: warning: function returns address of local variable

Status
Not open for further replies.

svar

Programmer
Aug 12, 2001
349
GR
I sthis a problem? Basically I want to return
a pointer to a struct from a function,
so I create a temporary struct in the function, fill it and pass a pointer to it back.
i.e.
*mystruct=somefunction(x1,x2,...);

structuretype * somefunction(x1,x2,...){

structuretype temporary=....
return &temporary}
 
hi svar,
the compiler is on right:
when the function returns (it finishes its life)
what it has built, comes destroyed, then that address
it returs is fake.
( automatic vars are allocated in the stack and when
the routine ends, pop(s) discards storage)

You have almost 2 solutions:

1) allocate struct area, outside routine, pass to it
its address, the routine loads it with correct value, ecc.

2) define, inside routine, the structure as "static":
in such mode, the area is allocated no in the stack,
but as a global var. When the routine returns, the area
and its address is hold and then you can refere it
also outside routine. If you call again the routine, the
value are still there: you can use this behavior, in counters, to test if it is 1st time you call, ecc.

bye
 
structuretype * somefunction(x1,x2,...)
{
...
structuretype* temporary = calloc/malloc/new/somethingElse;
...
return temporary;
}


Ion Filipski
1c.bmp
 
Don't forget to deallocate the memory when you've finished with it if you are using the calloc/malloc technique.
 
yes, take tare about allocated memory :) with delete/free, but memory leaks in my opinion are not the matter of the current question. Usualy the needed way to get some address of a some nonsystem data or for nonlogging purpose is to allocate memory in some way (see victorv:1). Beside of C/C++ native routines of allocating data, there are also some methods that deppends on application program interface you are using, for example CoCreateInstance (deallocate with interface->Release) or GetWindowDC (deallocate with ReleaseDC).

Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top