1

I found a similar question and solutions for that here - returning a local variable from function in C

But came up with another solution for same issue and would like to ask you to evaluate it, is it correct or not?

int myfunction (char **returnval) {
    int isvalue = 0;
    char *d;
    d = "Lorem";
    *returnval = d;
    return isvalue;
}


int main(int argc, char **argv) {
    int func_return;
    char *myvar;

    func_return = myfunction(&myvar);
    printf("myvar=[%s]\n", myvar);
    return 0;
}

Output: myvar=[Lorem]

Is that code correct? The memory used by vars won't be lost because of function scope?

Thank you.

Community
  • 1
  • 1
ihtus
  • 2,673
  • 13
  • 40
  • 58

2 Answers2

9

String literals are static, i.e. the memory used to hold the characters Lorem is not used to hold anything else for the duration of the program. Thus, returning an address to such a string is safe.

This is the same as doing

const char* myfunction(void)
{
  return "Lorem";
}

which is perfectly fine and a common thing to do, for instance when mapping enum values to symbolic strings:

typedef enum { Error_FileNotFound, Error_OutOfMemory, Error_PrinterOnFire } ErrorCode;

const char * error_code_to_string(ErrorCode error)
{
  switch(errorCode)
  {
  case Error_FileNotFound:
    return "Error_FileNotFound";
  case Error_OutOfMemory:
    return "Error_OutOfMemory";
  case Error_PrinterOnFire:
    return "Error_PrinterOnFire";
  return "Unknown error";
  }
}

Code like this is often (in practice) made way harder to read by making it more DRY, using macros to implement the case statements.

unwind
  • 391,730
  • 64
  • 469
  • 606
2

"Lorem" is static. as you can see, you never defined him in the code.

If you would have done:

char[6] d;

and you would copy there the value and try to return it you would have a problem

Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94