When a function ends are its local variables deallocated?

前端 未结 4 1376
日久生厌
日久生厌 2021-01-02 05:20

If not does that mean that I would have to end each function by deleting all local variables if I wanted to prevent 100% of memory leak?

4条回答
  •  爱一瞬间的悲伤
    2021-01-02 05:40

    If you manually allocate memory you must deleted it whenever you need,

    Example:

    char* foo()
    {
        char* manually_allocated_char  = new char(); // this will 'live' outside the function
        char  autamically_allocated    = 'a'; // this will be 'deleted'
        return manually_allocated_char;
    }
    
    
    void main()
    {
        char* a_new_char = foo();
        delete a_new_char; // You must free memory you have allocated for not having memory leaks
    }
    

提交回复
热议问题