This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

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
  • Yes - when using the stack for temporary storage, then that storage should obviously be in a part of the stack that the active call tree owns - which is why it is safe to have a buffer on the stack and send a pointer to that buffer to a function that gets called.

    But it is not safe to call a function that returns a pointer to a buffer in that functions stack space.

    The location of the buffer must be selected so that the lifetime of the buffer isn't shorter than the need for the buffer.

    char buf[100];
    snprintf(buf,sizeof(buf),"%u",value);
    


    The above have a local buffer and sends a pointer to that buffer to another function - i.e. the safe route to play with stack-allocated buffers.

Reply
  • Yes - when using the stack for temporary storage, then that storage should obviously be in a part of the stack that the active call tree owns - which is why it is safe to have a buffer on the stack and send a pointer to that buffer to a function that gets called.

    But it is not safe to call a function that returns a pointer to a buffer in that functions stack space.

    The location of the buffer must be selected so that the lifetime of the buffer isn't shorter than the need for the buffer.

    char buf[100];
    snprintf(buf,sizeof(buf),"%u",value);
    


    The above have a local buffer and sends a pointer to that buffer to another function - i.e. the safe route to play with stack-allocated buffers.

Children
No data