A garbage collector in C can be implemented using a dynamic array structure that tracks all allocated memory pointers, with a constructor to initialize the collector, an add function to register pointers for collection, and a collect function that iterates through the array and frees each registered pointer; this approach automates memory deallocation by maintaining a centralized list of dynamically allocated memory blocks that need to be freed when no longer in use.
Build a Garbage Collector in C from Scratch
Added:[Music] sup guys welcome to Today's Show so we're going to start by trying to fix the broken destroy tokens function or macro rather and I think I know I think I might know what's wrong I think the problem is I used the same variable name here as in the body of the function um so let's see we will open up a du block and let's see if I remember how I did this we had an in6 and and then we had a for Loop so four and we'll set n to Z we're going to loop as long as n is less than and this would be X do length um and then n++ [Music] right and at every iteration what are we going to do we're going to call D destroy token and we want to give this the X Dot's and this number and when that is done we want to free our XTS as well and let's not forget all these backslashes and at the end we'll just do a while false like so all right let's see if this works better this is another error message that we got the last time what if we were to do something like this instead so let's see we want to get it sorry we want to get it X do t plus n what if we just do that it compiles no still does not like this I wonder why this does not work because all of these T's are individually allocated because make token and all of this it derivates it allocates this oh wait a second the pointer is hidden inside of here right HTML contents start is equal to P that is what we're going to this destroy so let's do that so instead we do x uh T and then we do n so this is the token then we want to goe at contents and here it differs between the different types of tokens but they should all have the same position so what if we just um what if we just use that so if we create an additional parentheses and we take the address of this can we do that seems like but it still complains that it's an invalid pointer because we want to get at these These are the pointers we we want [Music] to remove so to speak but we don't want the address of this we want the content of this but can we really do this I'm not sure we can [Music] no what if we cast it to a void star go what if we were to assume that all of them are text tokens for ex for for example because if they were we could just do content dot text token like this and what if we were to cast it to a text to text star because the it should be able to free it the same way no matter what kind right or or what type it compiles double free [Music] why do they have the same address it does not make sense cont text token that's weird let's let's code something that tries to check that so let's comment this out for now and let's do something like well we can do basically the same thing um and we make a for Loop Set n to zero we loop as long as this is less than T dot length and n++ and then we do something like this let's also put in the index and this should be [Music] IDE [Music] in of T dot T do contents do [Music] content text token and we need to let's try this while Falls like so let's see what we get we got disconnected all right fortunately sociopath is very resilient if we just reconnect it should be fine save oh I need to save again that's right T do T is a point so why doesn't not complain about that in the other occasion oh let's put in the index as well now what do we get the same address why is that is this one of the Mals let's see okay this time we got another address so now look now look now look 51 b0 it's this one and why do we get that in every position wait a second this is a static variable so it does not remember the other addresses okay that's the problem okay do you really need M of this as well and if we do how do we store that but why does this work if that's the case because we save them here well you guys I believe we need to create a real garbage collector at least a simple enough version okay does so let's start by defining some structure let's call it garbage let's make this a dynamic array so what we'll have in here is the pointer P now we need to have an array of pointers so let's do a double star then and let's define the capacity and let's define the size so this is the garbage let's create a Constructor for this thing so we'll do garbage make garbage we don't need to have anything in [Music] here let's also make a definition what should we call it garbage collector block size perhaps not entirely accurate but good enough did I make it a pointer yeah so we'll start by calculating the size which will be the size of struct s garbage times garbage collector block size then we allocate this and we need to set the field as Fields as well so the p uh P will be equal to void double star zero the P capacity will be equal to the block size and the P size will be zero and then we return this so the that's a Constructor we need a function to add stuff to it as well let's call it add GC and it takes a void star so so void star [Music] pointer first we need to assert that we have a pointer well we need to give the argument of the garbage [Music] so if our garbage size is more or equal to the garbage capacity then we need to make this bigger then we need to have a [Music] size so the new size should be the size of struct as garbage times the capacity Plus the block size so we increase by 1,24 so then we'll do a rear look and we give the p and we give no not the p the G and we give the size assert that we have a p this should this should be G and pointer and then we can continue with our business um we also need to update the capacity so P let's not use P by the way it's easier to just modify this thing so the capacity will be be equal to the old capacity okay so we can do plus equals GC block size so now we will have room for adding this thing and the current size is the index we want to get at so the JP of J size will be equal to our pointer and then we will just increase the size simple enough so now we can add now we also need to do the actual garbage collection so we need a function let's just call it GC for garbage collection and we give the garbage so void GC and we have garbage G and what are we going to do well we need to have an N we'll need to do a for Loop where we set n equal to the [Music] G size minus one and as long as we have an N we're going to keep on looping and we're going to decrease this and at each iteration we simply do fre P GP of N and then we're going to read the whole thing and we need to have another of those because when we have freed it we need to create a new one so we'll make garbage and we'll return the P so this can this can't be avoid anymore because we need to return the new garbage like so and let's update this as well garbage star and we either need to give this garbage collector to every make token call yeah I think we're going to do that actually so garbage gar Garb garbs equal to make garbage we'll give it here garb so we need to update the signature of this [Music] make token so here we need to have the garbage let's see now we can't simply do this any longer we need to do something like token red and we'll set red equal to this for so before we return this thing we need to grab that pointer so basically we need to do similar to this so our pointer will be equal to the return [Music] content let's just pick one of those I think we can do this without a cast but how do we update the garbage do we need to return that as well or can we cheat and make it a global variable wait a second there's a second option isn't it we can send the actual reference and then then we can just do um well it's going to be gals add GC G pointer I suppose and then we'll just return the red I think this is going to work if we modify this slightly and do this and down here we can simply do GC G let's see what the compiler says about this void value not ignored as it ought to be LGC we made this a void okay so we need to do the same thing here we need to do this incompatible pointer type garbage double star maybe we don't need to do that I almost never use U function parameters as output variables so I'm not very used to this kind of stuff but um we'll figure it out okay P Undeclared 299 yeah it should be G uh G UND declared 354 I think we call it Garb here okay it compiled let's brace for impact huh I did not see that coming red is zero we switch on the type now we need to break before we had return here so we didn't need the brakes but we do now okay let's try again segmentation fult at least something new right and where does it crash it checks string loading of tml so basically we go to the make tag start so it's probably this ad GC that crashes though what do we do in the rgc ifj size is more or equal to the capacity which it shouldn't be so this two these two things it's is all it should do did we initialize this thing yeah we make the garbage and with send it to the functions it's weird that it shows this string length but we're not using that function we are using our own string length it must be this adgc that fails let's just try to comment it out temporarily yeah now it crashes when it tries to do the garbage collection but it's a very simple function g p g size before we do this let's print the size and the capacity of this thing so we have the G size and we have the G capacity size zero cap 1,24 so this is gp0 is equal to the pointer and that's a crash I suppose so if we do an exit zero right here it still crashes does not yeah oh wait a minute I thought about got this wrong we shouldn't make it like this we should make it like this and move it down here if it's possible to do that let's see if it is 285 all right so this should just be p p is equal to p r p is equal to zero let's do this maybe this all right it compiled and it did not crash 0 1 2 3 four five does it do the freeze yes it does all right you guys we have successfully pled a garbage collector easy as pie yeah I think that's it for this session thanks for watching thanks for today for
Up Next

Cello: A High-Level C Library for Experimental Programming
@TsodingDaily
63.4K views•2024-09-26

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

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

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


![[Q&A] 영상답변 | C언어 - 더블 포인터](https://i.ytimg.com/vi_webp/01Hp34c4qQE/maxresdefault.webp)









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






























