relation between C++ operators new/delete and malloc/free [duplicate] - c++

What is the difference between new/delete and malloc/free?
Related (duplicate?): In what cases do I use malloc vs new?

new / delete
Allocate / release memory
Memory allocated from 'Free Store'.
Returns a fully typed pointer.
new (standard version) never returns a NULL (will throw on failure).
Are called with Type-ID (compiler calculates the size).
Has a version explicitly to handle arrays.
Reallocating (to get more space) not handled intuitively (because of copy constructor).
Whether they call malloc / free is implementation defined.
Can add a new memory allocator to deal with low memory (std::set_new_handler).
operator new / operator delete can be overridden legally.
Constructor / destructor used to initialize / destroy the object.
malloc / free
Allocate / release memory
Memory allocated from 'Heap'.
Returns a void*.
Returns NULL on failure.
Must specify the size required in bytes.
Allocating array requires manual calculation of space.
Reallocating larger chunk of memory simple (no copy constructor to worry about).
They will NOT call new / delete.
No way to splice user code into the allocation sequence to help with low memory.
malloc / free can NOT be overridden legally.
Table comparison of the features:
Feature
new / delete
malloc / free
Memory allocated from
'Free Store'
'Heap'
Returns
Fully typed pointer
void*
On failure
Throws (never returns NULL)
Returns NULL
Required size
Calculated by compiler
Must be specified in bytes
Handling arrays
Has an explicit version
Requires manual calculations
Reallocating
Not handled intuitively
Simple (no copy constructor)
Call of reverse
Implementation defined
No
Low memory cases
Can add a new memory allocator
Not handled by user code
Overridable
Yes
No
Use of constructor / destructor
Yes
No
Technically, memory allocated by new comes from the 'Free Store' while memory allocated by malloc comes from the 'Heap'. Whether these two areas are the same is an implementation detail, which is another reason that malloc and new cannot be mixed.

The most relevant difference is that the new operator allocates memory then calls the constructor, and delete calls the destructor then deallocates the memory.

new calls the ctor of the object, delete call the dtor.
malloc & free just allocate and release raw memory.

new/delete is C++, malloc/free comes from good old C.
In C++, new calls an objects constructor and delete calls the destructor.
malloc and free, coming from the dark ages before OO, only allocate and free the memory, without executing any code of the object.

In C++ new/delete call the Constructor/Destructor accordingly.
malloc/free simply allocate memory from the heap. new/delete allocate memory as well.

The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.
There are other differences:
new is type-safe, malloc returns objects of type void*
new throws an exception on error, malloc returns NULL and sets errno
new is an operator and can be overloaded, malloc is a function and cannot be overloaded
new[], which allocates arrays, is more intuitive and type-safe than malloc
malloc-derived allocations can be resized via realloc, new-derived allocations cannot be resized
malloc can allocate an N-byte chunk of memory, new must be asked to allocate an array of, say, char types
Looking at the differences, a summary is malloc is C-esque, new is C++-esque. Use the one that feels right for your code base.
Although it is legal for new and malloc to be implemented using different memory allocation algorithms, on most systems new is internally implemented using malloc, yielding no system-level difference.

The only similarities are that malloc/new both return a pointer which addresses some memory on the heap, and they both guarantee that once such a block of memory has been returned, it won't be returned again unless you free/delete it first. That is, they both "allocate" memory.
However, new/delete perform arbitrary other work in addition, via constructors, destructors and operator overloading. malloc/free only ever allocate and free memory.
In fact, new is sufficiently customisable that it doesn't necessarily return memory from the heap, or even allocate memory at all. However the default new does.

There are a few things which new does that malloc doesn’t:
new constructs the object by calling the constructor of that object
new doesn’t require typecasting of allocated memory.
It doesn’t require an amount of memory to be allocated, rather it requires a number of
objects to be constructed.
So, if you use malloc, then you need to do above things explicitly, which is not always practical. Additionally, new can be overloaded but malloc can’t be.
In a word, if you use C++, try to use new as much as possible.

also,
the global new and delete can be overridden, malloc/free cannot.
further more new and delete can be overridden per type.

new and delete are C++ primitives which declare a new instance of a class or delete it (thus invoking the destructor of the class for the instance).
malloc and free are C functions and they allocate and free memory blocks (in size).
Both use the heap to make the allocation. malloc and free are nonetheless more "low level" as they just reserve a chunk of memory space which will probably be associated with a pointer. No structures are created around that memory (unless you consider a C array to be a structure).

new is an operator, whereas malloc() is a fucntion.
new returns exact data type, while malloc() returns void * (pointer of type void).
malloc(), memory is not initialized and default value is garbage, whereas in case of new, memory is initialized with default value, like with 'zero (0)' in case on int.
delete and free() both can be used for 'NULL' pointers.

new and delete are operators in c++; which can be overloaded too.
malloc and free are function in c;
malloc returns null ptr when fails while new throws exception.
address returned by malloc need to by type casted again as it returns the (void*)malloc(size)
New return the typed pointer.

To use the malloc(), we need to include <stdlib.h> or
<alloc.h> in the program which is not required for new.
new and delete can be overloaded but malloc can not.
Using the placement new, we can pass the address where we want to
allocate memory but this is not possible in case of malloc.

This code for use of delete keyword or free function. But when create a
pointer object using 'malloc' or 'new' and deallocate object memory using
delete even that object pointer can be call function in the class. After
that use free instead of delete then also it works after free statement ,
but when use both then only pointer object can't call to function in class..
the code is as follows :
#include<iostream>
using namespace std;
class ABC{
public: ABC(){
cout<<"Hello"<<endl;
}
void disp(){
cout<<"Hi\n";
}
};
int main(){
ABC* b=(ABC*)malloc(sizeof(ABC));
int* q = new int[20];
ABC *a=new ABC();
b->disp();
cout<<b<<endl;
free(b);
delete b;
//a=NULL;
b->disp();
ABC();
cout<<b;
return 0;
}
output :
Hello
Hi
0x2abfef37cc20

1.new syntex is simpler than malloc()
2.new/delete is a operator where malloc()/free()
is a function.
3.new/delete execute faster than malloc()/free() because new assemly code directly pasted by the compiler.
4.we can change new/delete meaning in program with the help of operator overlading.

Related

How to default-initialize without using new?

I am trying to implement my own std::vector container, and I am using realloc() to resize it, to prevent deletion and reallocation every time. With the following code:
buffer = new T[n]();
This would default initialize each element of the array, and allow me to start accessing them right away. However, since the standard specifies that the memory must be previously allocated by malloc(), calloc() or realloc() to use realloc(), I cannot use new.
I know that calloc() will zero-initialize the memory, but I am not sure if that will have the same behavior as new T[n](). What is the proper way to default-intialize with C style memory allocation?
First, no, zero-initializing memory is not the same as calling default constructors for the objects that that memory is supposed to hold. You have to call constructors. So malloc versus calloc doesn't matter in terms of correctness; so if you're going to go that route, use malloc -- it's faster.
Second, realloc won't work directly, because it doesn't know how to copy objects. Some objects can be copied byte-by-byte, and for those types, realloc is okay. But for most types, copying involves additional operations, and you have to use the copy constructor or copy assignment operator to do the copy. So realloc can be used in special cases, but not in general.
So, you're really limited to malloc and free, along with constructors (through placement new) and destructors.
You can call any constructor with any kind of memory using this syntax:
::new (ptr) T(...arguments go here (if any)...);
You may have to use
#include <new>
It will call the constructor of T for a memory allocated at ptr.
for an array you will have to loop:
T* ptr=(T*)malloc(sizeof(T)*n);
for(int i=0;i<n;++i)
::new(ptr+i) T();
But with this, DO NOT CALL delete ! You will have to explicitly call the destructor for each item and then free the memory with the correct function:
for(int i=0;i<n;++i)
(ptr+i)->~T();
free(ptr);
In case of realloc, you must be sure that the T object can be relocated without any problem (byte-to-byte copy OK). It should be safe for struct with simple data type.

Why don't malloc and ::operator new mix? [duplicate]

What is the difference between new/delete and malloc/free?
Related (duplicate?): In what cases do I use malloc vs new?
new / delete
Allocate / release memory
Memory allocated from 'Free Store'.
Returns a fully typed pointer.
new (standard version) never returns a NULL (will throw on failure).
Are called with Type-ID (compiler calculates the size).
Has a version explicitly to handle arrays.
Reallocating (to get more space) not handled intuitively (because of copy constructor).
Whether they call malloc / free is implementation defined.
Can add a new memory allocator to deal with low memory (std::set_new_handler).
operator new / operator delete can be overridden legally.
Constructor / destructor used to initialize / destroy the object.
malloc / free
Allocate / release memory
Memory allocated from 'Heap'.
Returns a void*.
Returns NULL on failure.
Must specify the size required in bytes.
Allocating array requires manual calculation of space.
Reallocating larger chunk of memory simple (no copy constructor to worry about).
They will NOT call new / delete.
No way to splice user code into the allocation sequence to help with low memory.
malloc / free can NOT be overridden legally.
Table comparison of the features:
Feature
new / delete
malloc / free
Memory allocated from
'Free Store'
'Heap'
Returns
Fully typed pointer
void*
On failure
Throws (never returns NULL)
Returns NULL
Required size
Calculated by compiler
Must be specified in bytes
Handling arrays
Has an explicit version
Requires manual calculations
Reallocating
Not handled intuitively
Simple (no copy constructor)
Call of reverse
Implementation defined
No
Low memory cases
Can add a new memory allocator
Not handled by user code
Overridable
Yes
No
Use of constructor / destructor
Yes
No
Technically, memory allocated by new comes from the 'Free Store' while memory allocated by malloc comes from the 'Heap'. Whether these two areas are the same is an implementation detail, which is another reason that malloc and new cannot be mixed.
The most relevant difference is that the new operator allocates memory then calls the constructor, and delete calls the destructor then deallocates the memory.
new calls the ctor of the object, delete call the dtor.
malloc & free just allocate and release raw memory.
new/delete is C++, malloc/free comes from good old C.
In C++, new calls an objects constructor and delete calls the destructor.
malloc and free, coming from the dark ages before OO, only allocate and free the memory, without executing any code of the object.
In C++ new/delete call the Constructor/Destructor accordingly.
malloc/free simply allocate memory from the heap. new/delete allocate memory as well.
The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.
There are other differences:
new is type-safe, malloc returns objects of type void*
new throws an exception on error, malloc returns NULL and sets errno
new is an operator and can be overloaded, malloc is a function and cannot be overloaded
new[], which allocates arrays, is more intuitive and type-safe than malloc
malloc-derived allocations can be resized via realloc, new-derived allocations cannot be resized
malloc can allocate an N-byte chunk of memory, new must be asked to allocate an array of, say, char types
Looking at the differences, a summary is malloc is C-esque, new is C++-esque. Use the one that feels right for your code base.
Although it is legal for new and malloc to be implemented using different memory allocation algorithms, on most systems new is internally implemented using malloc, yielding no system-level difference.
The only similarities are that malloc/new both return a pointer which addresses some memory on the heap, and they both guarantee that once such a block of memory has been returned, it won't be returned again unless you free/delete it first. That is, they both "allocate" memory.
However, new/delete perform arbitrary other work in addition, via constructors, destructors and operator overloading. malloc/free only ever allocate and free memory.
In fact, new is sufficiently customisable that it doesn't necessarily return memory from the heap, or even allocate memory at all. However the default new does.
There are a few things which new does that malloc doesn’t:
new constructs the object by calling the constructor of that object
new doesn’t require typecasting of allocated memory.
It doesn’t require an amount of memory to be allocated, rather it requires a number of
objects to be constructed.
So, if you use malloc, then you need to do above things explicitly, which is not always practical. Additionally, new can be overloaded but malloc can’t be.
In a word, if you use C++, try to use new as much as possible.
also,
the global new and delete can be overridden, malloc/free cannot.
further more new and delete can be overridden per type.
new and delete are C++ primitives which declare a new instance of a class or delete it (thus invoking the destructor of the class for the instance).
malloc and free are C functions and they allocate and free memory blocks (in size).
Both use the heap to make the allocation. malloc and free are nonetheless more "low level" as they just reserve a chunk of memory space which will probably be associated with a pointer. No structures are created around that memory (unless you consider a C array to be a structure).
new is an operator, whereas malloc() is a fucntion.
new returns exact data type, while malloc() returns void * (pointer of type void).
malloc(), memory is not initialized and default value is garbage, whereas in case of new, memory is initialized with default value, like with 'zero (0)' in case on int.
delete and free() both can be used for 'NULL' pointers.
new and delete are operators in c++; which can be overloaded too.
malloc and free are function in c;
malloc returns null ptr when fails while new throws exception.
address returned by malloc need to by type casted again as it returns the (void*)malloc(size)
New return the typed pointer.
To use the malloc(), we need to include <stdlib.h> or
<alloc.h> in the program which is not required for new.
new and delete can be overloaded but malloc can not.
Using the placement new, we can pass the address where we want to
allocate memory but this is not possible in case of malloc.
This code for use of delete keyword or free function. But when create a
pointer object using 'malloc' or 'new' and deallocate object memory using
delete even that object pointer can be call function in the class. After
that use free instead of delete then also it works after free statement ,
but when use both then only pointer object can't call to function in class..
the code is as follows :
#include<iostream>
using namespace std;
class ABC{
public: ABC(){
cout<<"Hello"<<endl;
}
void disp(){
cout<<"Hi\n";
}
};
int main(){
ABC* b=(ABC*)malloc(sizeof(ABC));
int* q = new int[20];
ABC *a=new ABC();
b->disp();
cout<<b<<endl;
free(b);
delete b;
//a=NULL;
b->disp();
ABC();
cout<<b;
return 0;
}
output :
Hello
Hi
0x2abfef37cc20
1.new syntex is simpler than malloc()
2.new/delete is a operator where malloc()/free()
is a function.
3.new/delete execute faster than malloc()/free() because new assemly code directly pasted by the compiler.
4.we can change new/delete meaning in program with the help of operator overlading.

Does using malloc in method, free in main work?

I have the following question:
If I use malloc in a method, return the pointer to my main, and free the pointer in my main, do i have successfully freed the memory or not? And is this bad programming style, if i do so?
int* mallocTest(int size)
{
int * array = (int*) malloc(size);
return array;
}
int main ()
{
int* pArray = mallocTest(5);
free (pArray);
return 0;
}
EDIT: The main purpose of this question is that I want to know, if I freed the memory successfully (if i use the right "combination" of malloc-free/new[]-delete[]) when i split this into the method and the main function!
EDIT2: Changed code and topic, to lead to the intended point of the question
Mixing malloc freeing it with delete is explained in other answers.
I feel you want to know if malloc memory allocated in a method, return the pointer to main, and free the pointer in main will work or not ? Yes it can be done and free will clear the memory allocated in other methods provided you have the pointer pointing to that location.
No. Use free to free memory allocated with malloc, delete for single objects allocations with new and delete [] when using new on arrays.
Mixing and matching may appear to work (it's undefined behaviour, and "undefined" included "works fine" and "sort of works fine most of the time, but crashes on thursdays in months starting with M on days that are divisible with 3 or 7 and the operator has shirt with stripes") - and may indeed work on SOME types of systems, but fail on others, depending on exactly how malloc and new and their respective free and delete functions are implemented.
It is fine to call a function that returns a pointer to some memory that is later freed with the appropriate call. It is "nicer" if you actually implement a pair of functions, where one allocates and the other destroys the data. This is particularly important if the data-structure allocated isn't trivial (e.g. you have allocations inside the outer allocation).
Also consider what happens if you decide that "Oh, I'd like to use new int[size]; instead of malloc(size * sizeof(int)); in the mallocTest()". Now every place that calls mallocTest() will have to change so that it calls delete [] instead of free that you corrected it to after reading this answer.
[Just spotted that your code is broken, and probably won't compile, certainly won't allocate space: (int *)malloc[size]; doesn't do what you want it to do, and I'm pretty sure is illegal, as indexing a function is invalid]
And finally, the "best" solution is wrap all allocations in an object, such that the destructor of that object destroys the data allocated within the object. So, for example, use std::vector<int> instead of allocating with malloc.
No - thats undefined bahaviour which means it might look like it works but actually it does not, for malloc() you should always use free(). Use delete[] only for memory allocated with new[].
You can actually check it yourself, new[] calls void* operator new(size_t) method which should be somewhere declared in your platform headers. The easiest way is to spy on whay it does with debugger, under VS2005 it calls in the end HeapAlloc function.
For deallocation you have void operator delete[](void*) which also must be defined somwhere. On VS2005 it calls HeapFree.
I checked what malloc/free calls, and those are also HeapAlloc and HeapFree.
So in my case it looks like it would work, because malloc looks like its implemented in the same way as new[]. But the point is that there is no magic here, new[] should be paired with delete[], malloc() with free(), because you never know how those are implemented on given platform.
When you dynamically allocate memory either using malloc or new, you
are "reserving" a part of the heap memory for a particular purpose.
The memory will remain "reserved" until you return it to the heap
using free or delete (depending on what you used for allocation).
That being said, you can allocate memory from anywhere in the program
and f*ree it from anywhere*. it's important however to be sure and do
both if you forget to free the allocated memory you get memory leaks
Actually, you should use free with malloc, delete with new, but to me, it is not because of undefinedness, that it may blow a nuclear bomb, invoke nasal demons or whatever. (Or simply, maintenance nightmares) malloc and new don't do the same thing at all. To simplify what is actually a bit more complicated:
malloc, inherited from C, allocates a chunk of memory. Period.
new T allocates a correctly-sized chunk of memory intended to store an object of type T (possibly through malloc), and executes the object's constructor.
Conversely:
delete ptr executes the destructor of the object pointed-to by ptr and releases the related chunk of memory.
free(ptr) releases the chunk of memory. Period.
For the universe not to fall apart, every call to a constructor must match a call to the destructor. That's a guarantee of the language. (and one of the greatest strengths of C++)
That's why every call to malloc must match a call to free, because free was made to undo what malloc did. And every call to new must match a call to a delete because delete was made to undo what newdid.

Why use malloc/free, when we have new/delete?

What is the use of malloc and free when we have new and delete in C++. I guess function of both free and delete is same.
They're not the same. new calls the constructor, malloc just allocates the memory.
Also, it's undefined behavior mixing the two (i.e. using new with free and malloc with delete).
In C++, you're supposed to use new and delete, malloc and free are there for compatibility reasons with C.
In C++, it is rarely useful that one would use malloc & free instead of new& delete.
One Scenario I can think of is:
If you do not want to get your memory initialized by implicit constructor calls, and just need an assured memory allocation for placement new then it is perfectly fine to use malloc and free instead of new and delete.
On the other hand, it is important to know that mallocand new are not same!
Two important differences straight up are:
new guarantees callng of constructors of your class for initializing the class members while mallocdoes not, One would have to do an additional memset or related function calls post an malloc to initialize the allocated memory to do something meaningful.
A big advantage is that for new you do not need to check for NULL after every allocation, just enclosing exception handlers will do the job saving you redundant error checking unlike malloc.
First, when you speak of new and delete, I assume you mean the
expressions, and not the operator new and operator delete functions.
The new and delete expressions are not related to malloc and
free, and only manage memory incidentally; their main role is to
manage object lifetime: a new expression will call the operator new
function to obtain memory, and then call the constructor; a delete
expression will call the destructor before calling operator delete to
free the memory. For the most part, objects should be created, and
not simply allocated, which means using the expressions exclusively.
There are some rare cases where one wants to separate allocation and
initialization (creation); implementing things like std::vector is a
classical example, where you'll allocate for many objects in one go, but
only construct one at a time. In such cases, you'll use the operator
new function for allocation, and placement new for initialization; at
the other end, you'll explicitly call the constructor (something like
p->~T()) for destruction, and use the operator delete function to
free the memory.
Off hand, I can only think of two cases where you'd use malloc and
free in C++. The first is to implement your own replacements of the
::operator new and ::operator delete functions. (I often replace
the global ::operator new and ::operator delete with debugging
versions, which trace allocations, put guard zones around the allocated
memory, etc.) The other is when interacting with a legacy library
written in C: if the library says to pass a pointer to memory allocated
by malloc (because it will free it itself using free), or more
commonly, returns a pointer to memory allocated by malloc, which
you're expected to free, then you must use malloc and free. (The
better libraries will provide their own allocation and deallocation
functions, which do more or less what the new and delete operators
do, but there will always be things like strdup().)

What is the difference between new/delete and malloc/free?

What is the difference between new/delete and malloc/free?
Related (duplicate?): In what cases do I use malloc vs new?
new / delete
Allocate / release memory
Memory allocated from 'Free Store'.
Returns a fully typed pointer.
new (standard version) never returns a NULL (will throw on failure).
Are called with Type-ID (compiler calculates the size).
Has a version explicitly to handle arrays.
Reallocating (to get more space) not handled intuitively (because of copy constructor).
Whether they call malloc / free is implementation defined.
Can add a new memory allocator to deal with low memory (std::set_new_handler).
operator new / operator delete can be overridden legally.
Constructor / destructor used to initialize / destroy the object.
malloc / free
Allocate / release memory
Memory allocated from 'Heap'.
Returns a void*.
Returns NULL on failure.
Must specify the size required in bytes.
Allocating array requires manual calculation of space.
Reallocating larger chunk of memory simple (no copy constructor to worry about).
They will NOT call new / delete.
No way to splice user code into the allocation sequence to help with low memory.
malloc / free can NOT be overridden legally.
Table comparison of the features:
Feature
new / delete
malloc / free
Memory allocated from
'Free Store'
'Heap'
Returns
Fully typed pointer
void*
On failure
Throws (never returns NULL)
Returns NULL
Required size
Calculated by compiler
Must be specified in bytes
Handling arrays
Has an explicit version
Requires manual calculations
Reallocating
Not handled intuitively
Simple (no copy constructor)
Call of reverse
Implementation defined
No
Low memory cases
Can add a new memory allocator
Not handled by user code
Overridable
Yes
No
Use of constructor / destructor
Yes
No
Technically, memory allocated by new comes from the 'Free Store' while memory allocated by malloc comes from the 'Heap'. Whether these two areas are the same is an implementation detail, which is another reason that malloc and new cannot be mixed.
The most relevant difference is that the new operator allocates memory then calls the constructor, and delete calls the destructor then deallocates the memory.
new calls the ctor of the object, delete call the dtor.
malloc & free just allocate and release raw memory.
new/delete is C++, malloc/free comes from good old C.
In C++, new calls an objects constructor and delete calls the destructor.
malloc and free, coming from the dark ages before OO, only allocate and free the memory, without executing any code of the object.
In C++ new/delete call the Constructor/Destructor accordingly.
malloc/free simply allocate memory from the heap. new/delete allocate memory as well.
The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.
There are other differences:
new is type-safe, malloc returns objects of type void*
new throws an exception on error, malloc returns NULL and sets errno
new is an operator and can be overloaded, malloc is a function and cannot be overloaded
new[], which allocates arrays, is more intuitive and type-safe than malloc
malloc-derived allocations can be resized via realloc, new-derived allocations cannot be resized
malloc can allocate an N-byte chunk of memory, new must be asked to allocate an array of, say, char types
Looking at the differences, a summary is malloc is C-esque, new is C++-esque. Use the one that feels right for your code base.
Although it is legal for new and malloc to be implemented using different memory allocation algorithms, on most systems new is internally implemented using malloc, yielding no system-level difference.
The only similarities are that malloc/new both return a pointer which addresses some memory on the heap, and they both guarantee that once such a block of memory has been returned, it won't be returned again unless you free/delete it first. That is, they both "allocate" memory.
However, new/delete perform arbitrary other work in addition, via constructors, destructors and operator overloading. malloc/free only ever allocate and free memory.
In fact, new is sufficiently customisable that it doesn't necessarily return memory from the heap, or even allocate memory at all. However the default new does.
There are a few things which new does that malloc doesn’t:
new constructs the object by calling the constructor of that object
new doesn’t require typecasting of allocated memory.
It doesn’t require an amount of memory to be allocated, rather it requires a number of
objects to be constructed.
So, if you use malloc, then you need to do above things explicitly, which is not always practical. Additionally, new can be overloaded but malloc can’t be.
In a word, if you use C++, try to use new as much as possible.
also,
the global new and delete can be overridden, malloc/free cannot.
further more new and delete can be overridden per type.
new and delete are C++ primitives which declare a new instance of a class or delete it (thus invoking the destructor of the class for the instance).
malloc and free are C functions and they allocate and free memory blocks (in size).
Both use the heap to make the allocation. malloc and free are nonetheless more "low level" as they just reserve a chunk of memory space which will probably be associated with a pointer. No structures are created around that memory (unless you consider a C array to be a structure).
new is an operator, whereas malloc() is a fucntion.
new returns exact data type, while malloc() returns void * (pointer of type void).
malloc(), memory is not initialized and default value is garbage, whereas in case of new, memory is initialized with default value, like with 'zero (0)' in case on int.
delete and free() both can be used for 'NULL' pointers.
new and delete are operators in c++; which can be overloaded too.
malloc and free are function in c;
malloc returns null ptr when fails while new throws exception.
address returned by malloc need to by type casted again as it returns the (void*)malloc(size)
New return the typed pointer.
To use the malloc(), we need to include <stdlib.h> or
<alloc.h> in the program which is not required for new.
new and delete can be overloaded but malloc can not.
Using the placement new, we can pass the address where we want to
allocate memory but this is not possible in case of malloc.
This code for use of delete keyword or free function. But when create a
pointer object using 'malloc' or 'new' and deallocate object memory using
delete even that object pointer can be call function in the class. After
that use free instead of delete then also it works after free statement ,
but when use both then only pointer object can't call to function in class..
the code is as follows :
#include<iostream>
using namespace std;
class ABC{
public: ABC(){
cout<<"Hello"<<endl;
}
void disp(){
cout<<"Hi\n";
}
};
int main(){
ABC* b=(ABC*)malloc(sizeof(ABC));
int* q = new int[20];
ABC *a=new ABC();
b->disp();
cout<<b<<endl;
free(b);
delete b;
//a=NULL;
b->disp();
ABC();
cout<<b;
return 0;
}
output :
Hello
Hi
0x2abfef37cc20
1.new syntex is simpler than malloc()
2.new/delete is a operator where malloc()/free()
is a function.
3.new/delete execute faster than malloc()/free() because new assemly code directly pasted by the compiler.
4.we can change new/delete meaning in program with the help of operator overlading.