what are malloc and free functions
malloc and free functions
or (memory allocating / mangement) functions
if you dont know about how ram works basicly its like a big chunk of rooms
where each room store 1 byte and its addressed with special number called (address)
each ram is limited to specifec amount of rooms which is the amount of bytes
this ram contain SO when you have 16 Giga byte ram its 17179869184 bytes (almost)
anyways so what about the functions ?
when calling malloc() function it takes an int input "malloc(int)"
which is how many bytes you want to allocate
why even do this ?
because your operating system offers limited space for each program to use
so when a program uses more than what is allowed to use the program well crash
so what this function actualy do is ask the system for some space to be used
now how does the function work ?
void* malloc(int)
it takes 1 parameter int which is the amount of bytes you need
and returns a void*
basicly void* is the address of that space but without specifing
what is stored in there so its just like (its a pointer to something)
you can just cast it to what ever type you are going to give that space for
for example if you are making some space for class that uses 16 bytes
you just do it like that
class_name var* = (class_name*)malloc(16); //the "new" operator handles all this for you
now we know how to use malloc and what is it used in
what about free ?
basicly free is just like telling the system
(hey iam done using that space you can use it in any thing else)
and it takes 1 parameter which is the pointer to your variable
free(void*);
what well happend if you allocated a space then didn't free it ?
it well just be there forever not used
(and considered used for the user by your program)
and it well be a bad memory mangement because you are wasting space that is not used
also the space well be used until the process is killed (when your program is ended)
what happend if you lost the value of the pointer ?
well this space well be there forever without you being able to delete it untill
you end your program
[important note : malloc may fail doing its job so when this happens it will just return 0 pointer or nullptr]
thanks for reading and hope that was helpful :)