Explain: new(), delete(), malloc(), free().

Asked By 0 points N/A Posted on -
qa-featured

What is the definition of the following term: new(), delete(), malloc(), free(). Hi, what are the differences between them? In the above terms which is better in the C++ perspective? Please write me with example.

SHARE
Best Answer by Riley weaver
Answered By 10 points N/A #93805

Explain: new(), delete(), malloc(), free().

qa-featured

Hi Shorif,

  • The new keyword is used for dynamic memory allocation in C++.

Its syntax is

pointer= new data_type;

and for array,

pointer=new data_type [ number_of_elements];

for e.g.

s=new int

s=new char[10]

  • The delete command is used to free the memory allocated dynamically.

its syntax is,

delete pointer_name

  • Malloc is used for dynamic memory allocation. Its syntax is,

pointer = (char*) malloc (1);

  • Free() is used to free the dynamically allocated memory.

its syntax is

free(Pointer_name)

  • Malloc and free are better in terms of C++ perspective. As they are used in general.

Hope this helped…..

Best Answer
Best Answer
Answered By 10 points N/A #93806

Explain: new(), delete(), malloc(), free().

qa-featured

Hello Shorif,

All the functions here are about allocation and freeing the memory space. New function also called as new operator. It allocates a memory space for a data type like integer, float, array etc. This works in a pointer and by calling this operator you can allocate or reallocate some space for that type on the memory.

Syntax is simply like

Var= new datatype();

 Now come to delete(), this is also an operator and it clears the allocated space for a pointer.

In this case the syntax is like

Delete var;

Malloc() and free() this two operators work as dynamic allocator and freeing the allocation. If you start a malloc operator somewhere than must have to free that with a free() operator. Because that will be reallocated by the malloc() operator again.

Simply the syntax is:

Datatype *var= (datatype *) malloc(number * sizeof(datatype));

And for freeing that memory the syntax is:

Free(var);

Mostly free and malloc are most convenient operators. These are widely used in professional level.

Thank you,

Riley weaver

Related Questions