Search code examples
cpointersheap-memorystack-memory

What is String Table in C?


char *p = "one two three";

Apparently, the string constant in this code is stored in the string table. What is "string table"? Is it in the heap or on the stack?

Information Background: I found this info in Teach Yourself C, by Hilbert Schildt, at chapter 6 (Using Pointers).

As you know, C allows string constants enclosed between double quotes to be used in a program. When compiler encounters such a string, it stores it in the program's string table and generates a pointer to the string. For this reason, the following program is correct and prints - one two three.

#include<stdio.h>
int main(void){
  char*p = "one two three";
  printf(p);
  return 0;
}

Solution

  • What the cited paragraph means, is a separated section of your program. These string constants are neither in the stack nor on the heap.

    Think about these kinds of sections a program may use to store stuff (common names of sections defined in the executable's file format in parentheses):

    • The machine code to execute (.text);
    • Static read-only values, for example static const variables (.rodata);
    • Static read-write variables with non-zero initial values (.data);
    • Static read-write variables with zero'ed initial values (.bss);
    • The stack to hold return addresses, function parameters, local variables, and so on; sometimes these are separated;
    • The heap, if there is one at all.

    String constants commonly fall in the category "static read-only values". Some compiler systems separate them from non-string values.

    Any compiler system may have these sections or not, but they are quite common.

    Anyway, abstract from this implementation detail. It will only help you if you need to go that deep, and you need to know how your specific compiler system works.

    On the abstract level, we can differentiate two cases:

    const char* p = "one two three";

    The string constant is stored somewhere, and its address is assigned to p. If you overwrite this variable with another value, you will lose the address.

    An extra space is needed for the variable p. Where this is, depends on the variable.

    const char a[] = "one two three";

    The string constant is stored somewhere, too. The array is allocated at this place. As long as a is visible, you can access its characters.

    Final note: Characters of a string constant are read-only. Always declare your respective variable with const char.