Return Pointer to local string, destroys the string or not?

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()?

Parents
  • Data on the stack will live until it is reused, which is likely to happen on the next function call. Regarding this, there is no difference between a PC or an embedded environment. Interrupts and other tasks use their own stack.
    Nevertheless, this is a risky situation where later additions to the code may destroy the data, because the programmer is not aware where the data is stored.
    Making the array static, as Franc suggested, will of course work and decrease stack usage, which normally is kept short on embedded systems.
    For clarity, it seems to be advisable to turn things round: Introduce the array earlier in the call chain (static or on stack), and pass pointer to it and size to "ReadNandFlash".

    Martin

Reply
  • Data on the stack will live until it is reused, which is likely to happen on the next function call. Regarding this, there is no difference between a PC or an embedded environment. Interrupts and other tasks use their own stack.
    Nevertheless, this is a risky situation where later additions to the code may destroy the data, because the programmer is not aware where the data is stored.
    Making the array static, as Franc suggested, will of course work and decrease stack usage, which normally is kept short on embedded systems.
    For clarity, it seems to be advisable to turn things round: Introduce the array earlier in the call chain (static or on stack), and pass pointer to it and size to "ReadNandFlash".

    Martin

Children
More questions in this forum