Is there Garbage Collection in C and C++?

preview_player
Показать описание
---

Is there Garbage Collection in C and C++? // You aren't the first person to wonder about automatic memory cleanup in C. Why don't we have garbage collectors like they do in other languages? Let's talk about it.

Related Videos:

***

Welcome! I post videos that help you learn to program and become a more confident software developer. I cover beginner-to-advanced systems topics ranging from network programming, threads, processes, operating systems, embedded systems and others. My goal is to help you get under-the-hood and better understand how computers work and how you can use them to become stronger students and more capable professional developers.

About me: I'm a computer scientist, electrical engineer, researcher, and teacher. I specialize in embedded systems, mobile computing, sensor networks, and the Internet of Things. I teach systems and networking courses at Clemson University, where I also lead the PERSIST research lab.

More about me and what I do:

To Support the Channel:
+ like, subscribe, spread the word

Рекомендации по теме
Комментарии
Автор

Technically C++ versions from C++11 up to and including C++20 have reachability-based garbage collection and leak detection specified in the standard, but no compilers have ever implemented it. It is going to be removed in C++23.

FintasticMan
Автор

CPP does call an objects destructor once it goes out of scope, so you can write memory freeing logic in the destructor.

EvilSapphireR
Автор

C an C++ are low level languages where you have (almost) total control. Once you add a memeory garbage collector to a language you lose a bit of control because the garbage collector decides when memory is freed. This opens the door for many other problems concerning performance, predictability, etc.

Ba-gbbr
Автор

I never had to worry about memory leaks anymore since I started using std::unique_ptr and std::shared_ptr. These two classes release the burden on the programmer about managing the heap allocated memory.

erick_falker
Автор

Your videos are consistently among the absolute best tutorials on C/C++ that I've ever seen on YouTube. I have a lot of experience in garbage-collected languages (e.g. C# and Java) but not any in unmanaged languages, so I'm slowly teaching myself C (and C++, later), in large part through your videos. Thank you for sharing your knowledge.

code
Автор

In C++ smart pointers are close enough to garbage collecting but they need to be opted in to manually and have some friction involved with them. In C try making memory pools. Bottom line is if you're using either C++ or C you probably care about performance and in most cases manually freeing memory helps you think about the memory layout of your program which is what you want anyways.

HairyPixels
Автор

I've started to learn C language focused on development of softwares for embedded systems. I've have already some experience in programming for scientific computing and machine learning algorithms purposes. So, this content has helped me a lot. Thank you, I wish success for you.

matheusdemoraes
Автор

I've created one library for this. It had a wrapper class to encapsulate pointer, it never exposes pointer to outer world, it just allows to interact with the object referred by the pointer. It can reference count and garbage collect automatically. It has one problem though, with circular references.

cipherxen
Автор

Wow, a lot to clarify IMO from this video!
1. C and C++ are so different it’s difficult to address both in these topics simultaneously
2. C++ DOES have managed pointers available (std::shared_ptr etc.) and a whole complex system with ref counters and move semantics… it’s not really garbage collection in sense of C# and other languages (e.g. you’ll need to take care to avoid circular references yourself!) and no reachability (mark and sweep) mechanism is running “collection” passes. But it does provide some ability to allow programmers to implement code without carefully keeping track of everything.
3. Of course you can write your own garbage collection in C++/C . You have power and flexibility in these languages and that is a feature of the language. With power comes responsibility. For example, Casting scenarios mentioned in this video are common in the lower levels of game engines as well as use of pointer arithmetic to move a pointer to the next address of a contiguous memory array of objects (though a hard coded +68 would be strange to see in code, but not clear how that slide in this video is relevant)
4. Many C++ Game Engines implement garbage collection. Check out Unreal Engine for example. The spirit of comments in the video indicate that people have “tried”, but not succeeded. These game engine implementations have shipped hundreds if not thousand so of games.
Bottom line, C/C++ do not have garbage collection systems built into the language like C#, Java, etc. But C++ does have ref counted smart pointers. If you want a full garbage collection system of course you can build it yourself.

foomoo
Автор

you could use in front of the declaration of your variables to call `cleanup_function` on it when the variable gets out of scope, but you have to initialize that variable or else it's undefined behavior, and you can also use `__attribute__((destructor))` on a function for it to be automatically called after main

leokillerable
Автор

I am interested in memory management, but appreciate that there is a performance cost. To paraphrase Scott Meyer, "there are many applications where you simply cannot run fast enough". Such as game graphics, numerical simulation, stock trading, ....am I sure there are many others. I think this is why native languages such as C & C++ will never lose popularity. That is why I always want to become proficient in an managed language and a native language with no memory management. Thank you for the insightful video.

billbez
Автор

As C++ has destructors, you can implement smart pointers, and it was already done (std::shared_ptr and family).
The real problem with C is that there is not a destructor (or drop function).

paivacn
Автор

smart pointers in cpp do this job quite efficient and fast. I haven't seen any performance bottleneck.

mazdakhng
Автор

std::unique_ptr and std::shared_ptr in C++ are solving the garbage collection problem

ZEdixchannel
Автор

Nice to hear what you said around 2:30. I see that question often in various forums, so it must be a very common misunderstanding. Why it isn't obvious to some people that the OS will reclaim all memory at program termination really puzzles me. Back in my CP/M days, the way to exit could simply be a jump to address 0, which would result in a reboot of the system.
I often think that the use of C++ with it's destructors, that 'must' be called, is causing anmoying problems, especially with large interactive graphical interface programs, in short: web browsers. I like to have my browser open at all times, I use many windows, and many tabs in each, I don't reboot my machime for months, and don't quit the browser unless the machine gets bogged down, which seems to happen more often over time. I use Firefox, because although Chrome may be a great browser, it doesn't seem to handle my usage pattern well. Firefox isn't perfect either, but at least it's better. Except when I decide it is leaking too much and needs a restart. I work on Linux, eith 8GiB RAM and just as much swap. But when it begins to use a good amount of swap, and I decide it's time, it takes an eternity for all the processes to quit. I guess it is because all parts of memory need to be swapped in for access just to run the destructors. This takes more than 10-15 minutes sometimes! If I just kill it, I suppose I run a little risk of having the persistent data messed up.
I just wish someone would teach programmers to persist any data (sessions, state etc) whenever possible and respond to a quit command by just calling exit right there and then, instead of returning all the way back to main, wasting _my_ time running futile destructors on gigabytes of objects along the way. If the program also did a check in the event loop that no more memory is being used than before (except for new tabs and windows), and that inactive windows are paused and have their state persisted and flushed until reactivated, I think things would work a _lot_ smoother, using just a fraction of the memory.
Maybe programmers should just be forced to program on machines with less memory for some time...

lhpl
Автор

For those looking for a garbage collection implementation for c++ take a look at Microsoft c++CLR (Common Language Runtime) it comes with the benefit that much of the .NET Framework(know from languages like c#, f# visual basic...) is already compatible with the garbage collection system implemented in c++CLR

redcrafterlppa
Автор

What was being described here was reference counting GC, and it is in widespread and common use in C++.

Not least on Windows, where it forms the core of the object lifecycle management of COM.

But smart pointers are also a form of garbage collection.

What C++ tends not to have is mark/sweep garbage collection. But there are libraries that do mark and sweep garbage collection in C/C++:

Christian-bcmy
Автор

I feel like C++ RAII is needed to accomplish this

SpeedingFlare
Автор

you are the rockstar programmer, learned lot things from you. thanks again!.

yjc
Автор

What about the Boehm-Demers-Weiser garbage collector? I read through some of the documentation some time ago, mostly out of curiosity. I've kept it in the back of my mind, just in case I ever felt the need for garbage collection with something, but I've never used it or needed it for anything. Still, it sounded promising, from what I remember reading of it. It basically works by replacing the call to malloc. I believe it's been around for a while and is the most noteworthy gc for C, though I have no idea how well of a job it actually does.

nunyobiznez