0

Function

char* getConnectDetail(int starting){
  String data;
  for(int i=0;i< 1024 ;i++) {
    if(EEPROM.read(i+starting) != 0){
    data += char(EEPROM.read(i+starting)); 
    }
   } 

   int str_len = data.length() + 1;
  char char_array[str_len];
  data.toCharArray(char_array, str_len);
  return char_array;
}

When I call it I get the garbage value... without creating the function there isn't any error.. Kindly solve it. I just want to know whats wrong with my returning method.

1
  • 1
    for future help with your internet searches, it is not an Arduino IDE function ... it is a C++ function
    – jsotola
    Commented Aug 18, 2019 at 20:33

1 Answer 1

1

char char_array[str_len]; is local to the function - it is created on function entry and its memory is released on function exit. The contents of that memory are undefined once it has been released and its data may or may not be valid.

If the caller creates data and passes it to the function, it survives the entire function call-and-return, and the caller will find the correct data in it. Another (less elegant) way to do it is to make data a global object, which again, gives it a lifetime greater that that of the function, but globals are subject to accidental over-writes and abuse by other functions, so they are not recommended unless they are truly the best solution in a given situation.

3
  • Good answer. Another alternative is to have the function malloc memory for the array and return that. Then the caller would be responsible for freeing it when it was done with it.
    – Duncan C
    Commented Aug 18, 2019 at 19:45
  • Also note that the OPs function will have to return the length of the string array somehow.
    – Duncan C
    Commented Aug 18, 2019 at 19:46
  • Since it no longer has to return the array (caller owns it), the return value is available to return a count or error code.
    – JRobert
    Commented Aug 18, 2019 at 22:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.