Search code examples
ccompiler-constructionc-preprocessorc-strings

Does the preprocessor prepare a list of unique constant strings before the compiler goes into action?


In the code below, I have two different local char* variables declared in two different functions.

Each variable is initialized to point to a constant string, and the contents of the two strings are identical.

Checking in runtime, the variables are initialized to point to the same address in memory.

So the compiler must have assigned the same (constant) value to each one of them.

How is that possible?

#include <stdio.h>

void PrintPointer()
{
    char* p = "abc";
    printf("%p\n",p);
}

int main()
{
    char* p = "abc";
    printf("%p\n",p);
    PrintPointer();
    return 0;
}

Solution

  • It has nothing to do with the preprocessor. But the compiler is explicitly allowed (not required) by the standard to share the memory for identical string literals. For details on when this happens, you must consult your compiler's documentation.

    For example, here's the relevant documentation for VC2013:

    In some cases, identical string literals may be pooled to save space in the executable file. In string-literal pooling, the compiler causes all references to a particular string literal to point to the same location in memory, instead of having each reference point to a separate instance of the string literal. To enable string pooling, use the /GF compiler option.