Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic memory allocation across programming languages

I have a question regarding dynamic memory allocation.

When it comes to C, memory is allocated using the functions malloc(), calloc() and realloc() and de-allocated using free().

However in objected oriented languages like C++,C# and Java, memory is dynamically allocated using the new and deallocated using delete keywords (operators) in case of C++.

My question is, why are there operators instead of functions for these objected oriented languages for dynamic memory allocation? Even when using new, finally a pointer is returned to the class object reference during allocation, just like a function.

Is this done only to simplify the syntax? Or is there a more profound reason?

like image 704
SoulRayder Avatar asked Sep 14 '26 07:09

SoulRayder


1 Answers

In C, the memory allocation functions are just that. They allocate memory. Nothing else. And you have to remember to release that memory when done.

In the OO languages (C++, C#, Java, ...), a new operator will allocate memory, but it will also call the object constructor, which is a special method for initializing the object.

As you can see, that is semantically a totally different thing. The new operator is not just simpler syntax, it's actually different from plain memory allocation.

In C++, you still have to remember to release that memory when done.

In C# and Java, that will be handled for you by the Garbage Collector.

like image 183
Andreas Avatar answered Sep 15 '26 21:09

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!