Look at this code :

char * function1() { return « hello » }

Where is stored hello string ? Is there a copy ?

What i want to avoid is to have a memory leak or accessing to another string instead of hello


  • What language is this code written in? What is the point of asking a question about "code" without specifying the language?
    – AnT
    May 11 '19 at 16:27
  • It is arduino c
    – Bob5421
    May 11 '19 at 16:28
  • Arduino C does not support «» quotes. In Arduino C return statement must end in ;.
    – AnT
    May 11 '19 at 16:30

String literals in C and C++ are stored in static memory, which in case of Arduino platform is ordinary data memory.

If we overlook the typos, your code is essentially equivalent to

char *function1()
  static char literal[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };
  return literal;

with a remark that in C and C++ you are not allowed to modify string literals. (Some nuances also depend on the specific language - C vs. C++ - which you failed to specify). Regardless of the language, it is always a better idea to use const char * pointers (as opposed to char *) to point to string literals.

There's no dynamic memory allocation here, and therefore no memory leaks possible. What you mean by "accessing another string" is not clear.

const char* function1() { return "hello"; }

Where is stored hello string ? Is there a copy ?

The string is compiled into the program memory. Before setup() is called the constant values are copied to the data memory (aka SRAM).

The function will return the pointer to the same string (memory location).

To save data memory the string literal can be access directly in program memory.

__FlashStringHelper* function1() { return F("hello"); }



  1. https://en.cppreference.com/w/cpp/language/string_literal
  2. https://www.nongnu.org/avr-libc/user-manual/pgmspace.html
  • Thanks but i do not understand. Should i use flashstringhelper and F() to make it work. It does not matter to me where the string is stored. I just want to read it from calling function
    – Bob5421
    May 11 '19 at 16:08
  • 1
    The first variant works nicely but will consume data memory. To avoid this the second variant can be used but it will require using special access functions. Please see the references. May 11 '19 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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