3

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?

SoulRayder
  • 5,072
  • 6
  • 47
  • 93
  • Different languages, different operators, different semantics (which is the important thing here, `new` in those languages does more than just allocate memory). – Some programmer dude Aug 15 '16 at 07:12
  • 1
    I wonder [why Java needs `new` at all](http://stackoverflow.com/questions/6340535/is-the-new-keyword-in-java-redundant). The usual non-authorative answer is "because C++" (which is funny, because `new` in C++ is quite often code smell). At some point the designers of Java thought it was a good idea (I am yet to be convinced it was.) And the designers of C# probably did it "because Java". – juanchopanza Aug 15 '16 at 07:43
  • 1
    I don't think there was a rationale. Stroupstrup saw how it was done in C and thought "hey, this is pretty stupid". And then next he thought "I'm sure I can come up with something dumber though!". And there you have it, programming language design for maximum bug potential... there's actually 4 operators: `new`, `new[]`, `delete` and `delete[]`. Mix them as you please. And they can be overloaded by the application programmer. As for Java and C# merely copy/paste the operator names from C++. And since they have garbage collection, they don't care about delete. – Lundin Aug 15 '16 at 11:37

5 Answers5

5

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.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

The whole point of Object Oriented design/programming is to provide meaningful abstractions.

When you are doing good OO design; you do not think (immediately) on areas in memory. One thinks about of objects; that carry state and provide behavior.

Even when writing code in C++, in most cases, I don't have to worry about subtleties like "why will my bits be aligned", "how much memory does one of my objects required at runtime" and so on. Of course, these questions are relevant in certain situations; but within OO design; the true value comes from creating useful abstractions that help to solve "whatever domain" problems as precise, easy, maintainable, ... as possible.

For the "keyword" versus "function" thing: just have a look at Java. The fathers of the language simply didn't want Java programmers start thinking about "memory pointers". You only deal with objects; and references to objects. Thus, the concept of "allocating" memory, and getting back a "pointer" simply does not exist at all here. So, how would you then provide this functionality as library method?! Well, if you would like to: you can't.

Finally, to a certain degree, this is a matter of "taste/style" by the people designing the language. Sometimes people prefer a small language core; and do everything in libraries; and other people prefer to have "more" things built-in.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Yeah OK. But why an operator instead of a function? – juanchopanza Aug 15 '16 at 07:15
  • "memory pointers" has nothing to do with operators vs. functions. In C++ a `new` expression return a pointer anyway. – juanchopanza Aug 15 '16 at 07:27
  • The questioner asked about **memory allocation**. He used those terms like 4 times; so I assume: it matters to him. – GhostCat Aug 15 '16 at 08:02
  • Yes, and? That doesn't change the fact "memory pointers" has nothing to do with the choice of operators vs. functions. – juanchopanza Aug 15 '16 at 08:06
  • There are **two** dimensions in his question. And my answer talks about both: A) the fact that "memory allocation" isn't a very useful concept in many OO languages B) regarding operator vs. method. So, what exactly are you complaining about? And if you think my wording could be improved; just edit my answer; and I will accept that if your edit adds value. – GhostCat Aug 15 '16 at 08:09
  • The whole point of OO is to provide a sound program design, no matter the purpose of the application. It has little to do with abstraction levels, or even with the programming language picked. OOD is about writing _autonomous_ classes, not abstract classes. It just happens that Java and C# are very high-level compared to C, but OO has nothing to do with that. – Lundin Aug 15 '16 at 11:42
0

I believe it's done solely to simplify the syntax as you've said. Operators are simply another way to call methods (or functions). using "12 + 13" is no different than using Add(12, 13). A way to see this is via the operator overrides in C# for example:

// Sample from - https://msdn.microsoft.com/en-us/library/8edha89s.aspx
public static Complex operator +(Complex c1, Complex c2)
{
    Return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}

It's a regular method but allows the usage of operators over complex classes. I'm using the Add operator as an example since I see it as no different than the memory allocation operators such as "new".

MichaelThePotato
  • 1,523
  • 2
  • 10
  • 19
  • In Java, I'm not sure how `T t = new T();` is simpler syntax than, say, `T t();`. – juanchopanza Aug 15 '16 at 07:40
  • 1
    I agree, but you could argue that the syntax `T t();` is a less clear for some than `T t = new T();`. This due to that fact that you don't visually assign a value to t in the first syntax. In the second you clearly state that t equals a certain value. – MichaelThePotato Aug 15 '16 at 07:44
  • Again, true. but the `T t = new T();` syntax can be more easily translated to the sentence "**t variable of type T now equals a new T**", instead of saying "**this t variable of type T is now equal to the function called by type T**", as you can see, it's less clear that way. The point is to make the syntax clearer to the highest amount of people. – MichaelThePotato Aug 15 '16 at 07:47
  • This makes sense from the point of view of people who are used to languages where you write `new` everywhere. That is the only reason the syntax is "clearer". Because it is what you are used to. – juanchopanza Aug 15 '16 at 07:50
  • I believe that since the higher the language, the easier it becomes, makes high languages such as C# more of an entry point to beginners, and so they should be easier to understand (I'm not saying that those who program in C# are dumb, I use C#). Being able to "translate" a line of code to a sentence of sorts makes the language easier. – MichaelThePotato Aug 15 '16 at 07:58
0

The new keyword is ideed to simplify the syntax, which is pretty suggestive and also does more than memory allocation, it invokes the constructor(s) also.

One thing you have said:

C++,C# and Java, memory is dynamically allocated and de-allocated using the new and delete keywords (operators)

for Java and C# it is only the new keyword, there is no delete. I know that in C# you are able to use using blocks to ensure that the resource will be released when the object is not used anymore, but this does not involves memory deallocation in every case, such as it's calling the Dispose method.

One more thing which needs to be pointed is that the goal of an object oriented programming language, as GhostCat just said, is to release the programmer to think of how memory is allocated in most of the cases, and more important, how are the objects released, this is why garbage collector was introduced.

The main principle is that as the programming language is higher, it has to abstract such things as memory management, and provide easy ways to solve the actual business problems one is looking for. Of course this might been considered when a programming langage is chosed for a specific task.

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
  • the `using` statement does nothing more than invoking the `Dispose()` method, which is a contract method of disposing unmanaged resources _(a C# feature)_. It must implement the `IDisposable` interface. It has nothing to do with freeing any object memory or so. – Jeroen van Langen Aug 15 '16 at 07:29
0

C :malloc calloc are basically the only ways in C to allocate memory.

  • malloc : it allocate uninitialized memory according to requested size without initializing it to any value
  • calloc : almost same as malloc ,plus it also initialize it to zero(0).

In both cases , you required something :

  • The requested memory size for allocation should be given at the time of initialization and it can be increase with realloc.
  • The allocated memory need to be deleted with free ,sometimes it can be result in a OOM error if somebody don't have a good memory to free the allocated memory although free is quite handy when you are doing lot of memory extensive work.

NOTE : Casting and size(to allocate memory) is required with malloc and calloc

C++: C++ also has malloc and calloc (free and reallocate too) along new and delete ,new and delete can think of as a modern way to allocate and free memory but not all of the OOP's based language have both. e.g java don't have delete.

  • new uses constructors to initialize default value so it's pretty useful while working with objects when you have various scenarios to set initial value using parameterize ,default or copy constructors.

NOTE : With new you don't have to do the appropriate casing unlike with malloc and calloc and no need to give a memory size for allocation. one less thing , right.

  • delete is used to release the memory, the delete call on some object also calls destructor which is the last place of the life-cycle of that object where you can do some farewell tasks like saving current state etc and then memory will be released .

Note : In C# and java the deallocation of memory is handled by Garbage-Collector who does the memory management to release the memory.It used various algos like mark-sweep to release the memory if there is no reference variable pointing to that memory or the reference variable value is set as null.

This may also lead to memory leak if there is a reference variable pointing to that object in memory which is no longer required.

The downside of GC is, this makes things slow

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68