Re: Who could tell me the difference between two code?

Tech-Archive recommends: Fix windows errors by optimizing your registry



tmp is on the stack and its scope is limited to the function,
once the function returns, the stack pointer moves, stack frame released
and the memory to which tmp initially referred to, is available for reuse
for other local variables and for possible use in stack frames for future
function calls.

Another way of doing this is to do like this:-
int* fn()
{
static int tmp=123;
return &tmp;
}

In this case although the name has a local scope the memory corresponding
to the variable tmp is available thoughout the lifetime of the program.

Another way is like this:-

int* fn()
{
int *tmp= new int;
*tmp = 123;
return tmp;
}

--
Vipin Aravind

"Lee Tow" <fbjlt@xxxxxxxxxxxxx> wrote in message
news:e8v3UnsMGHA.1616@xxxxxxxxxxxxxxxxxxxxxxx
Hello all:
Look:
int* fn()
{
int tmp=123;
return &tmp;
}
void main()
{
cout<<*fn()<<endl;
}
and when I compile the code,it display a warn:
returning address of local variable or temporary.
and look other code:
char* fn()
{
char *tmp="Hello";
return tmp;
}
void main()
{
cout<<fn()<<endl;
}
but it don't display a warn when I compile this code,
the both codes are very similar,but why do they display
different result?thank you.





.



Relevant Pages

  • Re: [PATCH] Documentation update sched-stat.txt
    ... int *cpus, int *domains, ... fprintf(stderr, "file format error 0\n"); ... if (tmp!= SCHEDSTAT_VERSION) { ... printf(" %.3f%% of remote wakeups come from domain%d\n", tmp, i); ...
    (Linux-Kernel)
  • Re: an interesting problem in c
    ... int *tmp = NULL; ... /* the allocation FAILED, but because we used tmp to detect ... it try to allocate memory at the end of the current chunk and if it ...
    (comp.lang.c)
  • Re: Help on TI C64x+
    ... int corrOut; ... short demod(short *restrict in, short *restrict qu, unsigned char ... tmp = _pack2; ... In this case the compiler will remove the dead code. ...
    (comp.dsp)
  • Re: Help on TI C64x+
    ... int corrOut; ... short demod(short *restrict in, short *restrict qu, unsigned char ... tmp = _pack2; ... In this case the compiler will remove the dead code. ...
    (comp.dsp)
  • [patch 06/23] locking: Convert __raw_spin* functions to arch_spin*
    ... unsigned long tmp; ... int ret = 0; ... unsigned long flags) ...
    (Linux-Kernel)