Cherple
Cherple

Reputation: 791

What happens to memory of variable after loops? (C++)

i'm trying to understand how C++ works. When u declare a new variable (int x) within a loop, for example within a for-loop. Memory is allocated to the variable x within the loop, but what happens to that memory after exiting the for-loop? My understanding from a friend is that Java will automatically de-allocate the memory, but what about C++?

Thanks.

Upvotes: 5

Views: 5920

Answers (3)

songyuanyao
songyuanyao

Reputation: 172924

Here're 3 possible cases in c++:

  1. Static memory, in which an object is allocated by the linker for the duration of the program. Global and namespace variables, static class members, and static variables in functions are allocated in static memory. An object allocated in static memory is constructed once and persists to the end of the program. For example:

    void f() {
        for (;;) { 
            static int i = 0; //memory will not be deallocated until the program ends.
        }
    }
    
  2. Automatic memory, in which function arguments and local variables are allocated. Each entry into a function or a block gets its own copy. This kind of memory is automatically created and destroyed when get out of its scope; hence the name automatic memory. Automatic memory is also said "to be on the stack.". For example:

    void f() {
        for (;;) { 
            int i = 0; //memory will be deallocated when get out of the loop's scope.
        }
    }
    
  3. Free store, from which memory for objects is explicitly requested by the program and where a program can free memory again once it is done with it (using new and delete). The free store is also called dynamic memory or the heap. For example:

    void f() {
        for (;;) { 
            int * pi = new int; //memory newed will not be deallocated until delete called.
                                //memory of the pointer self will be deallocated when get out of the loop's scope, same as case 2.
        }
    }
    

Upvotes: 1

user3553031
user3553031

Reputation: 6214

In C++, local variables are automatically destroyed when they go out of scope. If you declared the variable within a for loop, it will be destroyed when the loop exits or advances to the next iteration.

Note that this does not apply to objects allocated on the heap (for example, using new or std::malloc()); they need to be explicitly destroyed.

Upvotes: 1

freakish
freakish

Reputation: 56467

It will be deallocated if declared on stack (i.e. via int x = ...) and when the variable leaves its scope. It won't be deallocated if declared on heap (i.e. via int *x = new int(...)). In that case you have to explicitely use delete operator.

Upvotes: 7

Related Questions