[SOLVED] Memory failure while performing char c[] concatenations

I am trying to achive concatenation of several char c[], for what I build a function that accepts a pointer to an array of char c[], makes the concatenation, and returns a char r[] as result (a working sketch is attached at the end of this comment)
But what I am experimenting I can not understand... >:( The function seems to work properly in some defined cases, although what I change seems to me it should have no influence at all...

case A1 B1 B2 Result

1 no no no wrong
2 no no yes right
3 yes yes yes right

("no" means commented, "yes" means uncommented)
Notice that "debug" is defined in (A1) as false, so case (1) and (3) should behave the same...
Has anyone idea what is it hapenning here??
Thanks a lot!

//  Tested under environment: Arduino Wemos D1 (v1) (= UNO compatible)

boolean debug = false; // (A1)
char* concaten(char* g[], int n) {
  
    int L = 1;
    for(int i=0; i<n; i++) {
    if(debug)                                                                   // (B1)
            Serial.println("strlen(g["+(String)i+"]): "+ (String)strlen(g[i])); // (B2)
      L += strlen(g[i]);
    }
    
    char temp[L];
    for(int i=0; i<n; i++) {
      temp[i] = '\0'; // same as = (char) 0
    }
    
    strcpy(temp, g[0]);
    for(int i=1; i<n; i++) {
      strcat(temp, g[i]);
    }
    Serial.println("Intern: "+ (String)temp);
    return temp;
}

void setup() {

  Serial.begin(115200);
  delay(10);
  while (!Serial);
  
  char h0[] = "000";
  char h1[] = "11";
  char h2[] = "22222";
  char h3[] = "";
  char h4[] = "444444444";
  char* g[] = { h0, h1, h2, h3, h4 };

  int elements = sizeof(g)/sizeof(g[0]);
  Serial.println("Extern concaten: "+ (String)concaten(g, elements));
  
}

void loop() {
  ;
}

temp goes away when the function returns. You also have to add 1 to L to account for the trailing nul.

Functions cannot return C-style arrays. They can only modify them by reference or through pointers.

temp goes away when the function returns.

This means that you have to create temp before calling concaten, and pass it to the function.

  int L = 1;
  int elements = sizeof(g)/sizeof(g[0]);
  for(int i=0; i<elements; i++) L += strlen(g[i])+1;
  char temp[L];
  Serial.println("Extern concaten: "+ (String)concaten(temp, g, elements));

What everyone else said. To concatenate C strings, you need a buffer with enough room to hold the concatenated string and its trailing null. This buffer needs to have a lifetime that will last for as long as the result is to be used. What you are doing is a cause of countless C bugs over the decades. Often it works just fine 99% of the time, but 1% of the time there is an interrupt that scribbles over the stack. A nightmare to track down, because in some situations when you add debugging code the bug goes away.

Thank you very much All!
You saved me from this headache!