vipulmp
asked on
New & Malloc
Hello Friends,
I Want TO Know What Is Difference
Between New & Malloc?
Why We Explicitly Require Type Casting For Malloc Though It Returns
Void Pointer.
I Want TO Know What Is Difference
Between New & Malloc?
Why We Explicitly Require Type Casting For Malloc Though It Returns
Void Pointer.
Hi,
I just add that
- new is C++
- malloc is C
I just add that
- new is C++
- malloc is C
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi Akalmani,
Consider Following Eg
int main ( void)
{
int *p;
p = malloc ( sizeof (int));
p++;
return(0);
}
This Code Works Fine . Compiler Is Not
Giving Any Error Or Warning .
As We Are Receiving void * into int *
i.e int * = void *
As P is declared as int* compiler
already knows by how many bytes it should be incremented ie That Is By
Sizeof(int) Bytes .
I Have Two Another Differences
1> New With Size Option is Avalable
eg int *p;
p = new int[10];
2> New Calls Constructor.
Consider Following Eg
int main ( void)
{
int *p;
p = malloc ( sizeof (int));
p++;
return(0);
}
This Code Works Fine . Compiler Is Not
Giving Any Error Or Warning .
As We Are Receiving void * into int *
i.e int * = void *
As P is declared as int* compiler
already knows by how many bytes it should be incremented ie That Is By
Sizeof(int) Bytes .
I Have Two Another Differences
1> New With Size Option is Avalable
eg int *p;
p = new int[10];
2> New Calls Constructor.
> Compiler Is Not Giving Any Error Or Warning .
Your compiler is broken, or you don't have warnings turned on, or you compiled this as a C program and not a C++ program.
..B ekiM
Your compiler is broken, or you don't have warnings turned on, or you compiled this as a C program and not a C++ program.
..B ekiM
ASKER
Hi Friends,
Thank You ALL.
Thank You ALL.
There are differences between new and malloc
For malloc we need a type cast so that the compiler knows that what is the data type u are going to store in that memory, so that it can increment the pointer appropriately. Void pointers cannot be incremented.
New operator
1) It can be overloaded
2) It gives the appropriate datatype , no need of type cast
3) It can also initialize to the value that is passed
4) memory allocated using new has to be deleted using delete
Malloc
1) Its a lib function and cannot be overloaded
2) We need to typecast it explicitly
3) we cannot initialize to any value, but with calloc its initialized to zero
4) Memory allocated using malloc has to be freed using free()