How are string literals stored?

QuestionsQuestions8 SkillsProBuild Functions In CNov, 11 2025
0817

String literals are stored in a specific section of memory, typically in a read-only segment, depending on the programming language and the compiler. Here’s how they are generally stored:

  1. Read-Only Memory: In languages like C and C++, string literals are usually placed in a read-only section of memory. This means that once a string literal is created, it cannot be modified. Attempting to change a string literal can lead to undefined behavior or runtime errors.

  2. Null Terminator: In C and C++, string literals are automatically null-terminated. This means that a special character ('\0') is added at the end of the string to indicate its termination. This allows functions that operate on strings to determine where the string ends.

  3. Static Storage Duration: String literals have static storage duration, meaning they exist for the lifetime of the program. They are allocated when the program starts and deallocated when the program ends.

Example:

#include <stdio.h>

int main() {
    char *greeting = "Hello, World!"; // String literal

    printf("%s\n", greeting); // Output: Hello, World!
    
    // Attempting to modify the string literal (undefined behavior)
    // greeting[0] = 'h'; // Uncommenting this may cause a runtime error

    return 0;
}

In this example, the string literal "Hello, World!" is stored in a read-only section of memory. The pointer greeting points to this location.

If you have more questions about string literals or their storage, feel free to ask!

0 Comments

no data
Be the first to share your comment!