This forum may not be the best to ask the question, but the answers on the other forums (that i know) were generally with respect to C for desktop pc (where memory management is different from that in embedded) and this forum has knowledgeable embedded people. hence...
I was worried about the following situation:
void function1() { ... //other variables char* ptr = myary; ... ptr = ReadNandFlash("myfile"); ... } char* ReadNandFlash(char* Filename) { FILE* file; char temp_ary[256]; file = fopen(Filename, "r"); if(file == NULL) { return NULL; } while(!feof(file)) { fread(temp_ary, sizeof(char), 256, file); } fclose(file); return ary; }
will the 'temp_ary' be destroyed as only the pointer value is returned back to the function1()?
This should solve the problem:
char* ReadNandFlash(char* Filename) { FILE* file; static char temp_ary[256]; file = fopen(Filename, "r"); ... }
It may solve the problem, but it will keep the 256bytes of space always reserved. It want that 'temp_ary' be destroyed once the data is copied. one way is to use 'calloc/malloc' and 'free'.
other way is to pass the 'myary' to 'ReadNandFlash()'. But i was still curious about the lifetime of data in the memory.
Google for automatic variables and you will find the answer to your question.
Returning an address to an auto variable is not something that is different between embedded and PC - it is something that isn't part of the language standard. In short: it is invalid code that in some situations might work. Do you want invalid code that might in some situations happen to work?
other way is to pass the 'myary' to 'ReadNandFlash()' This will work.
What you are trying to do may/may-not destroy the array data in the memory. But there is no guarantee of it working always. There may be other piece of code which may change the data (other piece of code can be threads, or may be even an badly written ISR)
...may be even an badly written ISR)
May even be well written ISR!
Yes - for processors that has a common stack for ISR and main code (this includes a lot of processor architectures), the ISR is guaranteed to overwrite auto variables from returned functions.
And this thread is "Non-Specific (Generic)" so we can't assume any ARM chips that switches stack.
"it will keep the 256bytes of space always reserved. It want that 'temp_ary' be destroyed once the data is copied"
What, exactly, do you mean by "destroyed"?
"one way is to use 'calloc/malloc' and 'free'"
No, that would not physically "destroy" the data - it would still be there. And you'd still have to keep memory reserved for the Heap.
By "destroyed" i meant the data is over-written.
'free()' does not do that (unless you have some special version of it - in which case its documentation would tell you).
View all questions in Keil forum