I got a warning from vs2010 at compile time (C4172 returning local variable or temp)

int foo(){

int* bar = Bar()

}

int* Bar(){

int array[2];
array[0] = 1;
array[1] = 2;

return array;

}

if I understand the reason for this correctly, that the array 'array' in Bar function
is freed for use immediately after the return from the function.

My question is how to deal with this?

I'm wondering if using the static keyword will help..

int* Bar(){

static int array[2];
array[0] = 1;
array[1] = 2;

return array;

}

... and keep the address and its contents available to the calling function 'foo()'
until the function 'Bar()' is called again?

Just after a tip for the safest way to deal with it.

Appreciate any comments.

Recommended Answers

All 4 Replies

You could use the static keyword but I would create the array on the heap.

int* Bar(){

int * array = new int[2];
array[0] = 1;
array[1] = 2;

return array;

}

Just remember that you have to track and maybe delete [] this array.

It depends on who you want to manage the memory. If you have an agreement with the caller that the returned pointer is now 'owned' in the calling context then return dynamic memory as suggested by gerard4143. This requires that the contract be upheld or a memory leak will occur.
If you want to manage the memory within the function a static variable may be more of what you want.
It also depends on how you want to use the returned memory.
There is another option - you could pass in a buffer to be filled by the function avoiding the whole issue entirely. This is probably the safest route if you have control over the signature of Bar .

Ah! new, that never even crossed my mind, thanks for suggestion :)

I'm not that familiar with it either, am I correct in thinking that I can destroy the returned array variable from within the calling function after I have used it?

L7Sqr

Are you describing the caller passing an array by ref in your last suggestion?

<edit>

went with passing in a buffer to Bar()

Thank you both for your time and answers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.