Sorry for asking this question, but actually I don't know about this.
I have read in the following FAQ entry:
Can I free() pointers allocated with new? Can I delete pointers allocated with malloc()?
Furthermore, there is no guarantee that the mechanism used by new and delete to acquire and release raw memory is compatible with malloc() and free().
I just want to know that what is this "raw memory"?
Raw memory refers to the unmanaged memory in C and C++. malloc, calloc, realloc, and free are low-level functions that simply deal with raw memory.
You can also refer this Stanford document about Raw memory
"Raw memory" refers to blocks of memory, treated as unstructured arrays of bytes. Higher-level languages use these as the storage for objects; the program usually interacts with these objects, not the low-level byte values.
In C++, raw memory can be allocated dynamically using two different allocation functions:
operator new, used to allocate from the free store when you create an object using new
malloc from the C library
Memory allocated by new must be released with delete; and memory allocated with malloc must be released with free.
The line you quote explains that these might use different mechanisms to manage allocation; so that it's an error to use the wrong function to release memory (e.g. to allocate memory with new and try to release it with free).
In c you used malloc and free to allocate memory.
If malloc rerurned a pointer casted to void, you would have more or less raw memory. The cpp pendant is new and delete. There is also the possibility with special casts to get untyped memory, so called raw memory pointed to by raw pointers. But it is fact that any ressource allocated by new or new[] must be freed by delete resp.delete[]. BUT NOT THE MEMORY ALLOCATED BY REPLACEMENT NEW.
Related
This question already has answers here:
Closed 13 years ago.
What is the difference between "new" and "malloc" and "calloc" and others in family?
(When) Do I need anything other than "new" ?
Is one of them implemented using any other?
new and delete are C++ specific features. They didn't exist in C. malloc is the old school C way to do things. Most of the time, you won't need to use it in C++.
malloc allocates uninitialized memory. The allocated memory has to be released with free.
calloc is like malloc but initializes the allocated memory with a constant (0). It needs to be freed with free.
new initializes the allocated memory by calling the constructor (if it's an object). Memory allocated with new should be released with delete (which in turn calls the destructor). It does not need you to manually specify the size you need and cast it to the appropriate type. Thus, it's more modern and less prone to errors.
new/delete + new[]/delete[]:
new/delete is the C++ way to allocate memory and deallocate memory from the heap.
new[] and delete[] is the C++ way to allocate arrays of contiguous memory.
Should be used because it is more type safe than malloc
Should be used because it calls the constructor/destructor
Cannot be used in a realloc way, but can use placement new to re-use the same buffer of data
Data cannot be allocated with new and freed with free, nor delete[]
malloc/free + family:
malloc/free/family is the C way to allocate and free memory from the heap.
calloc is the same as malloc but also initializes the memory
Should be used if you may need to reallocate the memory
Data cannot be allocated with malloc and freed with delete nor delete[]
Also see my related answer here
new allocates and calls to ctor (the order is unspecified), delete the dtor and frees the memory allocated by a call to new
malloc only allocates some memory, and free deletes memory allocated by malloc
new may be implemented using malloc (not required though by the standard)
calloc does the same thing as malloc and also zero-initialises the newly allocated memory
As other posts have pointed out: malloc/free is part of C++ to be compatible with C.
Also see: Stroustrup: new vs malloc
You don't need anything other than new. It is a complete replacement for malloc in C++.
As for the difference: Malloc just allocates memory. New allocated memory and calls the constructors. Likewise free just releases the memory. Delete releases the memory and calls the destructor.
A word of warning: Don't mix the two idioms. The results are undefined.
Using new means that constructors will be called on the newly allocated memory. If the thing being allocated doesn't have constructors, new is functionally identical to malloc. and should normally be used in pereference to it.
new may or may not be implemented in terms of malloc - the C++ standard does not require either approach.
the main difference between new and malloc I can recall is that you cannot reallocate memory allocated by new using realloc. So if you wanted to increase/decrease the size of the memory block, you had to allocate a new block and copy everything over.
Calloc allows you to initialize the memory block you allocate while malloc does not.
When you new an object, space for the object is not only allocated but the object's constructor is called. But this is the C++ way its done, malloc is the old version way in C of allocating memory. calloc is the same as malloc, except for it clears memory to all bits zero.
do they become memory leaks or does c++ realize they have no pointers aiming at them and free up that memory? If they must be deleted i just use the delete command right?
does c++ realize they have no pointers aiming at them and free up that memory?
C++ does not "realize" any such thing. There is no built-in garbage collector.
If you allocate memory with new and don't free it with a corresponding call to delete, you have a memory leak.
Cody is correct, C++ does not have a garbage collector so you would have a memory leak when the pointer to the object is lost.
C++ does have something in the std library to address this. The std::shared_ptr will automatically delete the object if the object no longer has any std::shared_ptr pointed to it.
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.
This question already has answers here:
Closed 13 years ago.
What is the difference between "new" and "malloc" and "calloc" and others in family?
(When) Do I need anything other than "new" ?
Is one of them implemented using any other?
new and delete are C++ specific features. They didn't exist in C. malloc is the old school C way to do things. Most of the time, you won't need to use it in C++.
malloc allocates uninitialized memory. The allocated memory has to be released with free.
calloc is like malloc but initializes the allocated memory with a constant (0). It needs to be freed with free.
new initializes the allocated memory by calling the constructor (if it's an object). Memory allocated with new should be released with delete (which in turn calls the destructor). It does not need you to manually specify the size you need and cast it to the appropriate type. Thus, it's more modern and less prone to errors.
new/delete + new[]/delete[]:
new/delete is the C++ way to allocate memory and deallocate memory from the heap.
new[] and delete[] is the C++ way to allocate arrays of contiguous memory.
Should be used because it is more type safe than malloc
Should be used because it calls the constructor/destructor
Cannot be used in a realloc way, but can use placement new to re-use the same buffer of data
Data cannot be allocated with new and freed with free, nor delete[]
malloc/free + family:
malloc/free/family is the C way to allocate and free memory from the heap.
calloc is the same as malloc but also initializes the memory
Should be used if you may need to reallocate the memory
Data cannot be allocated with malloc and freed with delete nor delete[]
Also see my related answer here
new allocates and calls to ctor (the order is unspecified), delete the dtor and frees the memory allocated by a call to new
malloc only allocates some memory, and free deletes memory allocated by malloc
new may be implemented using malloc (not required though by the standard)
calloc does the same thing as malloc and also zero-initialises the newly allocated memory
As other posts have pointed out: malloc/free is part of C++ to be compatible with C.
Also see: Stroustrup: new vs malloc
You don't need anything other than new. It is a complete replacement for malloc in C++.
As for the difference: Malloc just allocates memory. New allocated memory and calls the constructors. Likewise free just releases the memory. Delete releases the memory and calls the destructor.
A word of warning: Don't mix the two idioms. The results are undefined.
Using new means that constructors will be called on the newly allocated memory. If the thing being allocated doesn't have constructors, new is functionally identical to malloc. and should normally be used in pereference to it.
new may or may not be implemented in terms of malloc - the C++ standard does not require either approach.
the main difference between new and malloc I can recall is that you cannot reallocate memory allocated by new using realloc. So if you wanted to increase/decrease the size of the memory block, you had to allocate a new block and copy everything over.
Calloc allows you to initialize the memory block you allocate while malloc does not.
When you new an object, space for the object is not only allocated but the object's constructor is called. But this is the C++ way its done, malloc is the old version way in C of allocating memory. calloc is the same as malloc, except for it clears memory to all bits zero.
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.