Problem with returning array of char

Hello ive got problem with returnning reference to char array from function. Its filled right bcs whene im printing it inside function it is printed well, but as i return in into loop and print it it prints just '?'.

Theres my code:

#include "mastermind.h"
#include "lcd_wrapper.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

void setup() {
  lcd_init();
  Serial.begin(9600);
  randomSeed(analogRead(1));

}

void loop() {
  
  
  char str=generate_code(false, 4);
  Serial.println(str);
  delay(1000);
  free(str);
}

And there is function that im calling :

char* generate_code(bool repeat, int length){
  
  if(length<1) return NULL;
  int randomnumber;
  char * key = (char *) malloc (length-1);
  for(int counter=0;counter<length;counter++){
    randomnumber=random(10);
    if(repeat==false){
      for(int a=counter-1;a>=0;a--){
        if(randomnumber==key[a]-'0'){
          randomnumber=random(10);
          a=counter;
        }
      }
    }
    key[counter]=randomnumber+'0';
    Serial.println(randomnumber);
    //delay(1000);
   
    
  }
  key[length]='\0';
  Serial.println(key);
  return key;
 }

Why are you malloc-ing less memory than you need?

generate_code is returning a char * not a char

  char *str=generate_code(false, 4);

Thanks you helped both its working, i dont whz i have malloc it i think that it was by mistake as i was tryin everything

If you allocate new memory with malloc() every time you call the function, you will eventually exhaust all the available memory. On many Arduinos, there isn't very much of that.

aarg:
If you allocate new memory with malloc() every time you call the function, you will eventually exhaust all the available memory. On many Arduinos, there isn't very much of that.

he does a free() in loop().

i agree using malloc() on an arduino doesn't make sense