C and C++ do not have built-in garbage collection because they are not type-safe languages; unlike garbage-collected languages like Java or Python that track references automatically, C/C++ allows any bit pattern to be cast as a pointer and permits pointer arithmetic, making it computationally expensive and impractical to implement garbage collection. Additionally, when a program terminates, the operating system automatically unmaps all memory anyway, so garbage collection at exit serves no practical purpose.
Does C or C++ Have Automatic Memory Management GC? | Explained
Added:does CN C++ have garbage collection or some kind of automatic memory cleanup and if not why let's take a [Music] look welcome back everybody I missed last week sorry about that things got a bit crazy but I'm back and today I want to answer a question by Kent to which reads wondering if you could discuss garbage collection at some point is there an auto cleanup of Malo Heap variables in in clang or GCC at any time of program termination how about manual cleaning at at Exit cheers so good question this is actually a question that I get a lot from new students especially students that are coming from a language like Java python Ruby something that has automatic garbage collection and so they're wondering do we have that here and if not why because having to manually free all of your pointers seems like a bit of a burden it seems a little tedious sometimes and so they want to know but so today I thought we would talk about why you don't really see a lot of garbage collection C and C++ and the reason's not that just nobody thought it was a good idea first of course I want to say thank you to all of you who helped support this Channel Through patreon where you can get access to source code and my monthly office hour also by buying merch taking courses subscribing telling your friends this channel keeps growing and that's wonderful and you keep helping me move it in the right direction so thanks so now back to memory see Ken's question here really is dealing with a few different things it's dealing with garbage collection yes but also a misunderstanding of the point of garbage collection and what happens when a program finishes so let's break this down and talk about these things separately so let's take the last one first why do we clean up memory at all this last part of Ken's comment talks about automatic memory cleanup using at exit so basically when the program exits we could have some code that goes through and tries to free all the different memory that's been allocated on the Heap and he also suggests that maybe compilers GCC or clang could have something built in that does this automatically when the program finishes now the key thing to understand here is that when your program finishes when it exits all memory everything on the stack everything on the Heap all your variables your code everything anything that's in memory and is not set as shared is going to be unmapped it's all cleaned up and it's not done by the compiler it's not done by the programmer it's not done by libc it's done by the operating system whenever a process terminates and this is of course assuming that you're on any kind of modern operating system whenever your process terminates the operating system is going to come through and unmap all of the p pages for all of the memory for that process anything that's not shared with another process and still in use so that's really important to keep in mind and with that in mind since that is actually happening there's really no point in looking at the exit of a program and going through and cleaning out all the memory like that's going to happen automatically we don't have to do it the operating system will do it for us now of course I'm not saying don't be in the habit of freeing your memory this is a very good habit to be in but my point is is that the reason that we free our memory is not because we don't want to leave it around at the end of the program the point is not the end of the program it's the middle of the program if I have a process that runs for a very long time we're talking days weeks months and if I'm not freeing my memory that memory can build up and it can build up to a point where my memory footprint is very large and that can impact performance so that's the point of freeing your memory and so if we do explore garbage collection we're not going to do it at the end of the process we want to do it in the middle but okay so let's assume that I have a c program maybe it's a web server anyway it's something that could run for a very long time hours days weeks months the question is could we make a garbage collector that will work with c and C++ and the answer is uh yeah sort of maybe to understand why let's take a look at how garbage collectors really work they typically work on the principle of reachability now let's say I have a data structure like a linked list like this right here you can see that I've allocated on the Heap now let's say I have a pointer it's either a global or a local variable that's pointing to the head of this list so my program through this pointer can reach this data structure it's reachable through that pointer and of course all of the other nodes are reachable through the next pointers now if I were working in Java or python or Ruby or some other garbage collected language the languages runtime would keep track of how many pointers or references there are to each block of memory so in this case each of my blocks of memory each node has one reference to it so in this case they would each have one and of course if I add a second reference to to the head of the list then the head node would now have a two stored in its reference counter since there are now two references pointing to it and as long as my nodes are reachable then they might be accessed later on in the program and so we need to keep them around we better not garbage collect them but as the program runs along things change and maybe one of these pointers gets pointed to something else and maybe this other pointer maybe that was a local variable and the function that it was declared in ends so that pointer goes out of scope and now it doesn't exist now note that each time one of those pointers stopped pointing to this block of memory the reference counter was decremented and now it is zero meaning that no references or pointers point to this block of memory so the head of the list is no longer reachable from the program so now at this point I can safely say that this node is garbage and I can clean it up and once it's gone then the next one can be cleaned up and so on until we've cleaned up the entire list now of course I'm definitely oversimplifying things a bit but this is basically how garbage collectors typically work and we could do this in CN C++ and some people have tried there's just one problem and that is that CN C++ are not type safe languages you see in Java a pointer or reference a reference a reference is a reference and that's never going to change in C or C++ on the other hand I can cast any set of bits anywhere in memory to be a pointer it's up to me of course to make sure that pointer points somewhere sensible if I don't my program might crash or seg fault but the point is that I can anything can become a a pointer in C and C++ and we also have pointer arithmetic so I can take an existing pointer and create new pointers from that pointer by saying something like p + 5 and again you want to be very careful with this usually po arithmetic in a normal correct program will not jump me from one allocated block on the Heap to another but it could the language allows it and it's possible that my program might be using one of these odd methods to access a block of memory on the heat and so if I try to make a garbage collector for C or C++ and it's trying to figure out what is reachable and what is not it has to consider every possible set of bits that could possibly be a pointer to each block on the Heap and that's going to be a huge pain very slow and probably not worth it of course you could make some rules for example you could say no pointer casting and no pointer arithmetic and then of course all you would have to do is update all pointer assignments or pointer operations and that would allow you to keep track of all the reference counts in your HEAP that will slow things down a little bit but hey fancy features in most languages do come at a small cost but the point is it would not be ridiculous and yes you could do it it is possible a few people have tried and I'll leave it to you and your favorite search engine to find examples out there they're they're not hard to find but I hope this helps you see why C and C++ typically are not garbage collected languages at least you're not getting anything with your compilers just right out of the box so I hope you learned something today like this video if you liked it and want to let the YouTube algorithm know that you want to see more content like this subscribe so you don't miss future videos check out my patreon if you want to get access to my office hour or source code for my videos and check out my courses I mean there's one right now one course there will be more coming but if you want to dig a little deeper and until next week I will see you later
Up Next

Custom Memory Allocator in C: From Scratch Tutorial for Developers
@dr-Jonas-Birch
7.2K views•2025-05-09

BitTorrent Protocol Explained: Piece Selection & Peer Choking
@StevenGordonAU
481 views•2013-02-22

Visualizing the Heap: A Deep Dive into Memory Allocators
@JacobSorber
40.7K views•2022-06-07

Enigma Machine Mechanics: WWII Encryption Explained
@JaredOwen
13.2M views•2021-12-11
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Computer Science



![Visualizing memory layout of Rust's data types [See description/first comment]](https://i.ytimg.com/vi_webp/rDoqT-a6UFg/maxresdefault.webp)






![#20. Операторы new / delete и new [] / delete [] | Язык С++ для начинающих](https://i.ytimg.com/vi/ECeoy6VjV4w/maxresdefault.jpg)




























