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;
}