Asked By
shorif
0 points
N/A
Posted on - 10/18/2011
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.
Answered By
stephen1
10 points
N/A
#93805
Explain: new(), delete(), malloc(), free().
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…..
Explain: new(), delete(), malloc(), free().
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