Does using malloc in method, free in main work? - c++

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.

Related

How compiler is going to know which memory is allocated using which operator or function?

Suppose I have allocated memory for two arrays, one using new operator and other using malloc function. As far as I know both of the memories are allocated in heap segment then my question is how the compiler is going to know which memory is allocated using which operator or function? Or is there any other concept behind this.
The compiler doesn't have to know how memory behind a pointer was allocated, it's the responsibility of the programmer. You should always use matching allocate-deallocate functions/operators. For example the operator new can be overloaded. In this case when you allocate object with new, and release it with free(), you're in trouble because free() has no idea what kind of book-keeping you have there. Here's simplified an example of this situation:
#include <iostream>
#include <stdlib.h>
struct MyClass
{
// Really dumb allocator.
static void* operator new(size_t s)
{
std::cout << "Allocating MyClass " << s << " bytes.\n";
void* res = Pool + N * sizeof(MyClass);
++N;
return res;
}
// matching operator delete not implemented on purpose.
static char Pool[]; // take memory from this statically allocated array.
static unsigned N; // keep track of allocated objects.
};
char MyClass::Pool[10*sizeof(MyClass)];
unsigned MyClass::N = 0;
int main(int argc, char** argv)
{
MyClass* p = new MyClass();
if (argc == 1)
{
std::cout << "Trying to delete\n";
delete p; // boom - non-matching deallocator used.
}
else
{
std::cout << "Trying to free\n";
free(p); // also boom - non-matching deallocator used.
}
}
If you mix and match the allocators and deallocators you will run into similar problems.
Internally, both allocation mechanisms may or may not finally use the same mechanism, but pairing new and free or malloc and delete would mix conceptually different things and cause undefined behaviour.
You must not use delete for malloc or free for new. Although for basic data types you might get away with it on most compilers, it is still wrong. It is not guaranteed to work. malloc and new could deal with different heaps and not the same one. Furthermore, delete will call destructors of objects whereas free will not.
Compilers don't have to keep track of which memory blocks are allocated by malloc or new. They might as a debug help, or they might not. Don't rely on that.
It does not know. It just calls a function that returns a pointer, and pointers do not carry the information of how they got to be or what kind of memory they point to. It just passes along that pointer and does not care about it any further.
However, the function you use to deallocate the memory (i.e. free/delete) might depend on information that got stored somewhere hidden by malloc/new. So if you allocate memory by malloc and try to deallocate it by using delete (or new and free), it might not work (apart from the obvious problems with constructors/destructors).
Might not work in this case it is undefined what happens. This is a huge bonus for cmpiler developers and performance, because they simply don't have to care. On the other hand, the effort is put off to the developers who have to keep track of how certain memory got allocated. The easiest way to do that is by using just one of the two methods.
new/delete is the C++ way to allocate memory and deallocate memory from the heap
whereas
malloc/free/family is the C way to allocate and free memory from the heap
I don't know why you want the compiler to know who allocated the heap memory but
if you want to track how there is a way.
One way of doing so is new would initialize the allocated memory by calling a constructor you can monitor this constructor to know who allocated the memory to heap.
Regards,
yanivx
As far as I know both of the memories are allocated in heap segment then my question is how compiler is going to know which memory is allocated using which operator or function?
What is this thing you call the "heap segment"?
There is no such thing as far as the C and C++ standards are concerned. The "heap" and "stack" are implementation-specific concepts. They are very widely used concepts, but neither standard mandates a "heap" or a "stack".
How the implementation (not the compiler!) knows where things are allocated is up to the implementation. Your best bet, and the only safe bet, is to follow what the standards say to do:
If you allocate memory using new[] you must deallocate it with delete[] (or leave it undeleted).
Any other deallocation is undefined behavior.
If you allocate memory using new you must deallocate it with delete (or leave it undeleted).
Any other deallocation is undefined behavior.
If you allocate memory using malloc or its kin you must deallocate it with free (or leave it undeleted).
Any other deallocation is undefined behavior.
Not freeing allocated memory can sometimes be a serious problem. If you continuously allocate big chunks of memory and never free a single one you will run into problems. Other times, it's not a problem at all. Allocating one chunk of memory at program start and oops, you didn't free it oftentimes is not a problem because that allocated memory is released when the program terminates. It's up to you to determine whether those memory leaks truly are a problem.
The easiest way to avoid these larger issues is to have the program properly free every single byte of allocated memory before the program exits.
Note well: Doing that doesn't guarantee that you don't have a memory problem. Just because your program eventually should free every single one of the multiple terabytes allocated over the course of the program's execution doesn't necessarily mean that the program is okay memory-wise.

How does delete[] keep track of the number of elements? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does delete[] “know” the size of the operand array?
How does the delete in C++ know how many memory locations to delete
I know it's a rather simple question but I a not sure about the difference (if any) between this lines :
double * a = new double[100];
delete[] a;
delete a;
free ((void*)a);
First off, would all of these calls (used each without the others) work the same way and free sizeof(double)*100 bytes?
Which lead me to the 2nd question, how does the program keep track of the size of the allocated memory? For instance if I send my a pointer to a function, then delete[] this pointer from within my function, would I also free the same amount of memory?
Thanks
The difference, oversimplified, is this:
delete[] a;
Is correct. All others are incorrect, and will exhibit Undefined Behavior.
Now, in reality, on all the compilers I use daily, delete a; will do the right thing every time. But you should still not do it. Undefined Behavior is never correct.
The free call will also probably do the right thing in the real world, but only because the thing you're freeing doesn't have a non-default destructor. If you tried to free something that was a class with a destructor, for example, it definitely wouldn't work -- the destructor would never be called.
That's one of the big differences (not the only difference) between new/delete and malloc/free -- the former call the constructors and destructors, while the latter meerly allocate and dealocate space.
Incorporating something #Rob said in his now-deleted post:
The simple rule is this: every new[] requires exactly one delete[].
Every new requires exactly one delete. malloc requires free. No
mix-and-match is allowed.
As to the question of how delete[] knows how many elements to delete, please see this response to a previous duplicate question.
Someone correct me, if I'm wrong, but as far as I understand, you use delete when you previously allocated memory with new and delete[] after using new Type[]. And free is used when you have allocated memory using malloc.
See c++ reference on delete and free.
Regarding the array of doubles, the result of all forms is the same -- all the allocated memory is returned to the system. The difference in calling free vs. delete vs. delete[] is:
free only releases the memory (the size of memory allocated for a was stored by memory manager when calling new)
delete calls the destructor of allocated object before releasing the memory
delete[] calls the destructor of each element in the array before releasing the memory
The difference is important if destructor of the allocated object contains cleanup code which releases other memory or system resource such as file or socket descriptor allocated during the lifetime of an object.
It is a good habit in C++ to allways use deleteon single instances and delete[] on array of objects/primitives regardless of the content of destructor.

relation between C++ operators new/delete and malloc/free [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.

How could pairing new[] with delete possibly lead to memory leak only?

First of all, using delete for anything allocated with new[] is undefined behaviour according to C++ standard.
In Visual C++ 7 such pairing can lead to one of the two consequences.
If the type new[]'ed has trivial constructor and destructor VC++ simply uses new instead of new[] and using delete for that block works fine - new just calls "allocate memory", delete just calls "free memory".
If the type new[]'ed has a non-trivial constructor or destructor the above trick can't be done - VC++7 has to invoke exactly the right number of destructors. So it prepends the array with a size_t storing the number of elements. Now the address returned by new[] points onto the first element, not onto the beginning of the block. So if delete is used it only calls the destructor for the first element and the calls "free memory" with the address different from the one returned by "allocate memory" and this leads to some error indicaton inside HeapFree() which I suspect refers to heap corruption.
Yet every here and there one can read false statements that using delete after new[] leads to a memory leak. I suspect that anything size of heap corruption is much more important than a fact that the destructor is called for the first element only and possibly the destructors not called didn't free heap-allocated sub-objects.
How could using delete after new[] possibly lead only to a memory leak on some C++ implementation?
Suppose I'm a C++ compiler, and I implement my memory management like this: I prepend every block of reserved memory with the size of the memory, in bytes. Something like this;
| size | data ... |
^
pointer returned by new and new[]
Note that, in terms of memory allocation, there is no difference between new and new[]: both just allocate a block of memory of a certain size.
Now how will delete[] know the size of the array, in order to call the right number of destructors? Simply divide the size of the memory block by sizeof(T), where T is the type of elements of the array.
Now suppose I implement delete as simply one call to the destructor, followed by the freeing of the size bytes, then the destructors of the subsequent elements will never be called. This results in leaking resources allocated by the subsequent elements. Yet, because I do free size bytes (not sizeof(T) bytes), no heap corruption occurs.
The fairy tale about mixing new[] and delete allegedly causing a memory leak is just that: a fairy tale. It has absolutely no footing in reality. I don't know where it came from, but by now it acquired a life of its own and survives like a virus, propagating by the word of mouth from one beginner to another.
The most likely rationale behind this "memory leak" nonsense is that from the innocently naive point of view the difference between delete and delete[] is that delete is used to destroy just one object, while delete[] destroys an array of objects ("many" objects). A naive conclusion that is usually derived from this is that the first element of the array will be destroyed by delete, while the rest will persist, thus creating the alleged "memory leak". Of course, any programmer with at least basic understanding of typical heap implementations would immediately understand that the most likely consequence of that is heap corruption, not a "memory leak".
Another popular explanation for the naive "memory leak" theory is that since the wrong number of destructors gets called, the secondary memory owned by the objects in the array does not get deallocated. This might be true, but it is obviously a very forced explanation, which bears little relevance in the face of much more serious problem with heap corruption.
In short, mixing different allocation functions is one of those error that lead to solid, unpredictable and very practical undefined behavior. Any attempts to impose some concrete limits on the manifestations of this undefined behavior are just waste of time and sure sign of the lack of basic understanding.
Needless to add, new/delete and new[]/delete[] are in fact two independent memory management mechanisms, which are independently customizable. Once they get customized (by replacing raw memory management functions) there's absolutely no way to even begin to predict what might happen if they get mixed.
It seems that your question is really "why heap corruption doesn't happen?". The answer to that one is "because the heap manager keeps track of allocated block sizes". Let's go back to C for a minute: if you want to allocate a single int in C you would do int* p = malloc(sizeof(int)), if you want to allocate array of size n you can either write int* p = malloc(n*sizeof(int)) or int* p = calloc(n, sizeof(int)). But in any case you'll free it by free(p), no matter how you allocated it. You never pass size to free(), free() just "knows" how much to free, because the size of a malloc()-ed block is saved somewhere "in front" of the block. Back to C++, new/delete and new[]/delete[] are usually implemented in terms of malloc (although they don't have to be, you shouldn't rely on that). This is why new[]/delete combination doesn't corrupt the heap - delete will free the right amount of memory, but, as explained by everyone before me, you can get leaks by not calling the right number of destructors.
That said, reasoning about undefined behavior in C++ is always pointless exercise. Why does it matter if new[]/delete combination happens to work, "only" leaks or causes heap corruption? You shouldn't code like that, period! And, in practice, I would avoid manual memory management whenever possible - STL & boost are there for a reason.
If the non-trivial destructor that are not called for all but the first element in the array are supposed to free some memory you get a memory leak as these objects are not cleaned up properly.
It will lead to a leak in ALL implementations of C++ in any case where the destructor frees memory, because the destructor never gets called.
In some cases it can cause much worse errors.
memory leak might happen if new() operator is overridden but new[] is not. same goes to the delete / delete[] operator
Apart from resulting in undefined behavior, the most straightforward cause of leaks lies in the implementation not calling the destructor for all but the first object in the array. This will obviously result in leaks if the objects have allocated resources.
This is the simplest possible class I could think of resulting in this behaviour:
struct A {
char* ch;
A(): ch( new char ){}
~A(){ delete ch; }
};
A* as = new A[10]; // ten times the A::ch pointer is allocated
delete as; // only one of the A::ch pointers is freed.
PS: note that constructors fail to get called in lots of other programming mistakes, too: non-virtual base class destructors, false reliance on smart pointers, ...
Late for an answer, but...
If your delete mechanism is simply to call the destructor and put the freed pointer, together with the size implied by sizeof, onto a free stack, then calling delete on a chunk of memory allocated with new[] will result memory being lost -- but not corruption.
More sophisticated malloc structures could corrupt on, or detect, this behaviour.
Why can't the answer be that it causes both?
Obviously memory is leaked whether heap corruption occurs or not.
Or rather, since I can re-implement new and delete..... can't it not cause anything at all. Technically I can cause new and delete to perform new[] and delete[].
HENCE: Undefined Behavior.
I was answering a question which was marked off as a duplicate, so i'll just copy it here in case it metters. It was said well before me the way memory allocation works, i`ll just explain the cause & effects.
Just a little thing right off google: http://en.cppreference.com/w/cpp/memory/new/operator_delete
Anyhow, delete is a function for a single object. It frees the instance from the pointer, and leaves;
delete[] is a function used in order to deallocate arrays. That means, it doesnt just free the pointer; It declares the whole memory block of that array as garbage.
That's all cool in practice, but you tell me your application works. You are probably wondering... why?
The solution is C++ does not fix memory leaks. If you`ll use delete without the parenthesises, it'll delete just the array as an object - a proccess which might cause a memory leak.
cool story, memory leak, why should i care?
Memory leak happens when allocated memory doesn't get deleted. That memory then requires unneccessary disk-space, which will make you lose useful memory for pretty much no reason. That's bad programming, and you should probably fix it in your systems.

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.