Home > Blockchain >  When variable will free in C program
When variable will free in C program

Time:03-14

In dynamic memory allocation, the memory which is used by malloc() and calloc() can be freed by using free(). In static memory allocation, when is the variable in main() freed from the program? In a tutorial, I learned that when the whole programs is finished then after all variables are freed from RAM. But someone tells me that when the program is long enough and variable is used early and after that if the variable has no use in the whole code then compiler will automatically free the variable before the end of program. Can someone please clarify if both statements are correct or not?

CodePudding user response:

As you can see in this question: Why does C not require a garbage collector?

Stephen C, the author of the answer says that:

The culture of these languages (C and C ) is to leave storage management to the programmer.

Would the correct answer be when the process is terminated all memory used is freed? I think yes. C compiler does not look for garbage or non reachable variables, this is a progammer work.

But I have read that C or C garbage collectors exists like Java, they can be useful but remember, the implementation will be slower.

Again, I recommend to you read the question I have attached at the beggining for more information.

CodePudding user response:

The language guarantees that the lifetime of a static storage duration variable is the whole program. So it can be safely accessed at any time.

That being said, the standard only requires the code produced by a conformant compiler to behave as if all language rules were observed. That means that for optimization purposes a compiler is free to release the memory used by a static variable if it knows that the variable will not be used passed a point. Said differently it is neither required nor forbidden and as a programmer you should not even worry for that except for very specific low level optimization questions.

Example:

...
int main() {
    static int arr[10240];
    // uses arr
    ..
    // no uses of arr passed this point - called B
    ...
}

The program shall behave as is the array arr existed from the beginning of the program until its end. But as long as arr is not used past point B, the compiler may reuse its memory, because there will be no change in any observable state.

This in only a low level optimization point allowed (but not required) by the as if rule.

  • Related