Search code examples
c++pointersmemory-managementstring-literalsconst-char

Is const char* automatically deleted when it is passed as an argument?


When I pass a const char* as a function argument (like this):

void print(const char* text)
{
     std::cout << text << std::endl;
}

Is it automatically deleted? If not, what happens to it, and how should I delete it?


Solution

  • A pointer variable is a variable that is pointing to some other memory.

    When you pass a pointer as argument to a function, the pointer itself is copied, but not the memory it is pointing to. Therefore there's nothing to "delete".


    Lets take this simple example program:

    #include <iostream>
    
    void print(const char* text)
    {
         std::cout << text << std::endl;
    }
    
    int main()
    {
        const char* text = "foobar";
    
        print(text);
    }
    

    When the main function is running you have something like this:

    +-----------------------+     +----------+
    | text in main function | --> | "foobar" |
    +-----------------------+     +----------+
    

    Then when the print function is called and running it have its own copy of the pointer:

    +-----------------------+
    | text in main function | -\
    +-----------------------+   \      +----------+
                                  >--> | "foobar" |
    +------------------------+   /     +----------+
    | text in print function | -/
    +------------------------+
    

    Two variables pointing to the same memory.

    Furthermore, literal strings like "foobar" in the example above will never need to be deleted or free'd, they are managed by the compiler and lives throughout the entire run-time of the program.