0

Just wondered what happens to the memory of local vars in a C program? I have a console application that runs 24hrs a day and want to make sure I free up memory safely.

Thanks Pete

Pete Jones
  • 46
  • 7
  • 4
    Don't describe your code. [Edit] your question and put some relevant code _there_. The question is not clear enough. – Jabberwocky Feb 21 '20 at 10:53
  • 3
    Basically you need to free explicitly only what has been allocated by `malloc`/ `calloc` and `realloc`. – Jabberwocky Feb 21 '20 at 10:56

1 Answers1

4

If you do not use dynamic memory allocations, nothing to worry about.

Local variables are created on the stack.

Stack is a preallocated memory region, you can think this way: local variables are mapped to stack.

In some cases, it makes sense to nullify local variables for security reasons.

You can also run Memory Sanitizer to check if memory leaks exist in the program.

Tarek Dakhran
  • 2,021
  • 11
  • 21
  • Theoretically you can fake dynamic memory allocations by abusing recursion. When you run out of memory it will then be in the form of a stack overflow. – MSalters Feb 21 '20 at 14:34
  • @MSalters : I do not see how recursion can be described as faking dynamic memory allocation. A stack overflow is just a different and unrelated kind of memory management error. – Clifford Feb 21 '20 at 21:15
  • @Clifford: The hypothetical `stackalloc` would take a continuation function as an argument, and never actually return to the caller. – MSalters Feb 22 '20 at 14:48