When a pointer is created in scope, what happens to the pointed to variable when the pointer goes out of scope?

前端 未结 4 1215
猫巷女王i
猫巷女王i 2021-01-02 16:14

The title says it all.

I found an old question that is essentially the same, but I needed a tiny bit further clarification.

In this question the accepted an

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 16:34

    The pointer itself occupies space on the "automatic storage" (which is usually the stack). It gets removed once the function returns [or the scope is finished, but technically, nearly all compilers will "wait" until the function returns before the space is freed].

    If you call the same function in a loop 1 million times, there will only be ONE pointer at any given time. If you have 1 million functions [and a lot of memory], there will be one pointer for each function that is currently called. E.g.

    char *foo()
    {
        char *text1 = "Hello";
        return text1;
    }
    
    void bar()
    {
        char *text2 = "World!";
        printf("%s %s!\n", foo(), text2);
    }
    
    
    void baz()
    {
        char *text3 = "Meh";
        bar();
    }
    
    int main()
    {
        char *text4 = "Main";
    
        baz();
    }
    

    When we enter main, text4 is created on the stack - it is initialized to the string "Main" which is held in some other bit of memory. When we then call baz(), text3 gets created and initialized to "Meh", which calls bar() that creates text2 and points to the text "World", and calls foo which creates text1 and initalizes to Hello. As foo returns, the address inside text1 is given as the return value, and the pointer itself goes away. When printf() is finished, bar returns, and the pointer goes away.

    The strings "Main", "Meh", "Hello" and "World" are still staying in place for as long as the program is running.

提交回复
热议问题