I know that C doesn't offer automatic garbage collection which means whenever someone allocates memory using malloc
, realloc
or calloc
, they will have to free them at the end of the program so there will be no leak. I, however, haven't seen anyone freeing a memory that was allocated during say variable declaration. For instance, if I do something like int x = 10;
, somewhere a memory to hold the value 10 is being allocated (I can even see the adress by doing &x
), but I never free such memories in my program, yet the seems to be no memory leak (if I use valgrind to check), which leads me to think that C have some kind of garbage collection, or is this a different kind of story?

- 877
- 1
- 7
- 28
-
1It's allocated beforehand in the EXE and then deallocated when the program unloads. There are plenty of guides showing how C's memory works for variables - static, local and dynamically allocated variables, for instance. Did you look at any? – Random Davis Oct 09 '20 at 18:48
-
I didn't know what to look for, thanks I will know look for static variables and things like that. Or is there a proper topic to the question I am asking. – EHM Oct 09 '20 at 18:54
-
1Unless you're on a deeply embedded system with no memory protection, all storage allocated by `malloc` and friends *is* automatically deallocated as a side effect of process termination, and tearing it all down by hand is just a waste of time. – zwol Oct 09 '20 at 19:07
5 Answers
After a function returns, the calling function adjusts the stack pointer. Any variables local to the calling function, located on the stack, are no longer considered part of the stack since the stack pointer has been adjusted.
Global and static variables are not destroyed until the program exits. At that point, the operating system will record that the memory no longer belongs to that process and it may be allocated to other processes, but typically will not zero it out. In both cases, the RAM just keeps its value until overwritten.

- 531
- 1
- 4
- 24
-
Good answer except for the part about the OS not zeroing out deallocated memory -- a user space process can't tell when this actually happens, but the OS *must* wipe RAM that was once used by one process before reallocating it to another process, for security reasons. – zwol Oct 09 '20 at 19:09
-
According to this, it is not a must https://stackoverflow.com/a/12716054/13826315, the 3rd paragraph – user10191234 Oct 09 '20 at 19:17
-
That 3rd paragraph is incorrect. It may have been true for Windows 3.1 and 95 but it has never been true for NT or any variation of Unix. – zwol Oct 09 '20 at 20:23
The C language standard defines 4 different storage durations which specify how memory is managed for various objects:
Objects with static storage duration are allocated when the program starts and are released when the program exits (i.e., the storage for the object remains static over the lifetime of the program, so you don't have to worry about it). Anything declared at file scope (outside of any body or function) or with the
static
keyword has static storage duration.Objects with automatic storage duration are allocated when program execution enters the block in which they are declared, and then are released when program execution exits that block (i.e., allocation and deallocation are "automatic", you don't have to worry about it). Anything declared within a function or block without either the
static
or_Thread_local
keywords has automatic storage duration. This is the group yourint x = 10;
belongs to. Most people will refer to such objects as being "on the stack", which works well enough as a shorthand description, but be aware that actual implementations can be much more complicated than that. What matters is the behavior, not how that behavior is typically implemented. Stacks makeauto
storage duration easy to implement, but they're not the only way to do it.Objects with thread storage duration are allocated when a thread is started and released when the thread exits. Anything declared with the
_Thread_local
keyword has thread storage duration. Since threads and thread semantics are a relatively new addition to the language, this doesn't really fit in with the "automatic vs. static" distinction above, but like the other two, you don't have to worry about managing that memory.Objects with allocated storage duration are allocated with a call to
malloc
,calloc
, orrealloc
and are released when you callfree
. These are the only things you have to watch out for with respect to memory leaks, and what would be managed by garbage collectors if C had garbage collectors. Most people will refer to such objects as being "on the heap", which works well enough as a shorthand description, but the actual implementation can be much more complicated. Again, what matters is the behavior, not how the behavior is implemented.
There are a number of good reasons why C doesn't currently have any sort of garbage collection system for dynamically-allocated memory. A future version of the language may create a new garbage-collected dynamic memory storage class, but I don't think that's likely.

- 119,563
- 19
- 122
- 198
While the existing answers are helpful, I think you may misunderstand something more fundamental.
I know that C doesn't offer automatic garbage collection which means whenever someone allocates memory using malloc, realloc or calloc, they will have to free them at the end of the program so there will be no leak.
That's actually not true.
Ask yourself this question: what happens to the memory needed for the program code -- the executable instructions -- when the program terminates? Who frees that?
The answer to the question is obviously not the program itself, not after it terminates! For a normal program (what the standard calls hosted) the operating system allocates a process, associates memory with it, loads the executable into that memory, and starts the program running. It manages resources requested from it by the program, including file handles and memory. When the program terminates, all associated resources are discarded, and the memory freed for other use.
When we talk about garbage collection and memory management, we're not talking about resources acquired from the operating system that it will free when the program terminates. We're talking about memory that the program acquires temporarily, uses, frees, and then re-acquires, cyclically. If circle is broken (by and by) and memory that could be freed is not, and then more memory that could be freed is not, cyclically, that is what we refer to as a leak. Garbage collection is the process of detecting when acquired cannot be accessed anymore and freeing it automatically.
if I do something like int x = 10;, somewhere a memory to hold the value 10 is being allocated
Yes. C calls that a definition, not declaration. A declaration merely says something exists; a definition makes room for it.
If the variable is defined outside a function, or in a function with static
, it's allocated once when the program is first loaded by the OS. Variables defined in a function and not marked as static are called automatic, and are allocated "on the stack" for the duration of the function. When the function terminates, they are "popped off the stack". It could be thought of as a kind of primitive garbage collection: because variables local to a function cannot be referenced from outside the function, clearly when the function terminates, they can be "collected". (I will now take cover, because 100 CS graduates are about to say that's not what "garbage collection" means, and they're right. I'm just trying to answer your question on your own terms.)
If you spend much time with C, sooner or later you'll bump into recursion, where a function calls itself. Each time it does that, more automatic variables are added to the stack. If it doesn't find a reason to stop, you have infinite recursion, and before long (a few seconds, usually) the stack is exhausted and something bad happens. The effect is very much like calling malloc(3) in an infinite loop, except that the memory comes from the stack instead of the heap.

- 7,574
- 1
- 16
- 31
-
it know made sense! when I asked the question I was thinking that a memory was tough to be leaked if it wasn't freed before the termination of the program. I mean that is still one kind of leak, but not the one I was taking about when I was talking about garbage collection. Thanks! – EHM Nov 21 '20 at 09:12
whenever someone allocates memory [...] they will have to free them at the end of the program
That isn't true at all, you don't need to free memory allocated inside of your process at the end of the program to avoid memory leaks.
if I do something like
int x = 10;
That doesn't allocate memory at all, it uses the thread's already allocated stack memory (or the .text
section if it's global) to store the value.
leads me to think that C have some kind of garbage collection
There's no garbage collection in C.

- 65,249
- 10
- 91
- 131
-
2Definitions do allocate memory, whether they are static and allocated in some data segment or automatic and allocated in a stack. Typical thread implementations do assign a region of memory for the stack, but portions of that stack are further allocated and released as functions are called and return. Each modification of the stack pointer is an allocation or deallocation of memory, even though it may be a bundled allocation for all the stack memory needed by one function call. – Eric Postpischil Oct 09 '20 at 18:52
-
I.. don't believe you're right, but feel free to show sources to back your claims up. As far as I know, thread stack space is allocated once and then set in stone, which is the reason why you get stack overflow exceptions -- the pre-allocated stack space is full and can't be increased. – Blindy Oct 09 '20 at 18:55
-
1C 2018 6.7 5: “A *definition* of an identifier is a declaration for that identifier that: — for an object, causes storage to be reserved for that object;…” – Eric Postpischil Oct 09 '20 at 19:02
-
1Re: “just increments and decrements”: What do you think allocation is? Allocation is just bookkeeping. You may be confusing allocation in general with dynamic allocation provided by `malloc`. Even there, it is just bookkeeping: `malloc` may have a bunch of memory available and, when a request is made, all it needs to do is adjust some records it has. The stack pointer is the same thing; it is a record of what memory has been allocated for a particular use and what has not. – Eric Postpischil Oct 09 '20 at 19:04
-
Ah, so it's semantics then. By memory allocation I meant memory that's given to you by the operating system. Without a variant of `malloc`, you would never be able to access more than your stack space (which is allocated by the OS) and the various sections (allocated by the OS at the behest of the loader). Stack variables will never be able to escape the block of stack memory given by the OS, but memory requested by `malloc` can and will. – Blindy Oct 09 '20 at 19:07
There are two ways to allocate memory in C: on the stack or on the heap. When you write something like:
int x = 10;
that is a stack allocation. That will be released as soon as the program exits the scope in which the declaration occurred. For example if the above line occurred in a function, it would be released at the end of the function.
If you use something like malloc to declare a variable, that is a heap allocation. This will not be automatically released when you exist the scope where it was declared. If you never call the corresponding clean up code, it will remain in memory until the program terminates (at which point of course it will be cleaned up by something external to the program).

- 70
- 8
-
C has five storage durations, not two: static, thread, automatic, allocated, and temporary. When explaining C semantics, it is preferable to use the terms in the C standard, such as “automatic” rather than “stack.” Stack is very commonly used to implement automatic storage, but other methods may be used in specialized environments. And a true heap structure is rarely used to implement allocated storage duration; the `malloc` family of routines may have sophisticated algorithms resulting from decades of research and development. – Eric Postpischil Oct 11 '20 at 14:32
-
@EricPostpischil you are correct, but people still refer to the stack and heap, even if they are misnomers. The heap is not an actual heap, but this is an implementation detail. – fishrec Oct 11 '20 at 23:38