Search code examples
cstringcompilationliterals

Memory allocation for same string literals


Consider this code:

int main(void)
{
    printf("%s", "the string");
    printf("%s", "the string");
}

Is there any standard saying that the program memory will be allocated only once for "the string" and not twice (or any other number of times, depending on how many times the literal is used)? When I examine the output elf file of my program, for such a case I can only find the string occurring just once and I am trying to figure out whether this is a rule, or is it compiler dependent.


Solution

  • Modern compilers and more recently link time optimizers automatically share string literals across modules or the whole program. There is no need for any particular indication in the code, but the programmer should not rely on this to always happen as some platforms or debugging modes might alter this behavior, that is indeed compiler dependent.