C - Freeing resources

I was wondering what is the function in C to free a resource(usually a variable)

I know in C# there a Garbage collector, but in c and C++ there are none.
I believe in c++ the function is free([resource name here]);

If it's dynamically allocated (via malloc(3) in C or new in C++) you can free(3) it. But it's not garbage collection per se, as you'll have to do it yourself.

so if I do say

int test;

should I have a?

free(test);

or is it for when you create pointers?

malloc(*pointer);

and how would you go about disposing of the freed memory, it's managed by the O/S ? or you have to manually write "null" to that memory address ?

You can't free an statically allocated variable (like your int test above), not in C nor Java nor C# or any other language. It's always valid until execution leaves the variables scope (usually the containing block or when an object is destroyed).

With malloc(3) you can allocate memory for an array or structure, which you can access via a pointer afterward. When you're done, use free(3) to return that memory to OS control. It's basically "ask the OS for control of a memory segment and return that control afterwards", no need to dispose of anything.

In C++ you'll use new and delete instead of malloc and free.

so it's essentially only if you want to reserve a segment of memory(to assure that it's always there) and to access via pointer later(not that I like using pointers)?

So the int would be freed after it hits the end of the block?

main
{
}<--would be freed here

Um, no. Statically allocated memory is always there, guaranteed (otherwise the program won't even start). Via malloc you ask the OS for some memory. If you get it, it's yours until you return it. If you don't your program has to cope with that (either complain to the user and/or try again later). It's the same in C#, if the VM doesn't have any memory left for objects you can't create them.

Good luck then, because in C/C++ there are very, very few things you can do without pointers. Arrays, for example:

char string[10];
string[3] = 'A';

is the same as

char *string = (char *)malloc(10 * sizeof(char));
*(string + 3) = 'A';

And modifying multiple values in one function/method without pointers is virtually impossible.

That's right.

would you have to free(string) after?

you would have to free(string) here no matter what right?

In the first case you won't have to free at the end, as it's statically allocated, in the second you would have to, since it's dynamically allocated. In the first case you'd have to recompile every time you want to change the size of the string/array, which can be done at runtime in the second case.

oh I see, so if you want an array with a dynamic size you have to use pointers where as the other one is done on compile time.

Thanks for the insightful information :slight_smile: I <3 c-type langs :slight_smile: