'In cpp, do I have to always "free" the primitive variables?

If I have a function that declares an int, in the end of this function I need to "free" that int to save memory?

Example:

void doSomething() {
    int x = 0;
    // do something with x
    free(x); // needed?
}
c++


Solution 1:[1]

No. It's an automatic variable, meaning it is deallocated when it goes out of scope.

Also, you rarely use free() in C++, it's a C function.

Solution 2:[2]

As everyone else has mentioned, no you would not need to free the memory specifically since the variable goes out of scope at the end of the function.

On a slightly different note, however, I came across this page while looking for a way to quickly and cleanly free the memory of primitive variables and later found an incredible way to do this that I didn't realize was a part of C++. For anyone else looking for this answer as well, here it is.

You can actually just use additional set of braces to set the specific scope of variables in C++, so one way to free the memory of "x" in this function without the end of the function would just be encasing the scope of "x" with braces like so:

void doSomething() {
    // do something in the start of the function
    {

        int x = 0;
        // do something with x

    } // x is destroyed here

    // do something that doesn't require x
}

Solution 3:[3]

No. The int object has automatic storage duration. It is destroyed at the end of its scope, i.e. when the function ends.

You should not be using free in C++ anyway. It is only used when you have used malloc to allocate memory, but malloc is not often used in C++. Instead, you should be using new to dynamically allocate objects. When you have created an object with dynamic storage duration with new, use delete to destroy it.

Solution 4:[4]

No

x is a stack variable and will be deleted automatically when doSomething() returns.

Only those objects allocated manually with malloc() must be free()d (very uncommon in C++). Also do not use free() and malloc() in C++ - use new and delete instead.

Solution 5:[5]

No you only need to free memory if u have allocate it dynamically using new . In this case this variable is in the stack and is destroyed when the functions ends.

Solution 6:[6]

You only need to free variables for which you have allocated memory in code. In your example x is declared locally, and the program allocates memory for it on the stack. At the end of the function, the variable is automatically destroyed. So you don't need to worry about it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 unwind
Solution 2
Solution 3 Joseph Mansfield
Solution 4 Community
Solution 5 Suvarna Pattayil
Solution 6 Zaphod