how to use malloc() in C++ [closed]
How to use malloc()
in C++ program?
You shouldn't use malloc
in C++. You should use new
instead.
In fact, you probably shouldn't be using new
as well (for most basic programming in C++). But still a basic example is declaring an array: int* array = new int[n]
. This will allocated room for n integers and return a pointer to the address of the first one. Please note that you must explicitly call delete[]
to free this allocation.
Mostly, you shouldn't use it at all. C++ provides the new
and delete
operators for memory management, and even delete
can be largely avoided by using smart pointers such as boost::shared_ptr
from the Boost library.
Example:
// malloc
Duck* duck = (Duck*)malloc(sizeof(Duck));
// new
Duck* duck = new Duck();
Also note that, if the Duck class has a non-trivial constructor, then new
is almost mandatory. (Almost, because you could use malloc
with placement new
, but that would be getting us off the main track).
Question 1: "How do I call malloc from C++?"
One of these two:
#include <cstdlib>
...
int *iptr = (int*) std::malloc(sizeof(*iptr));
#include <stdlib.h>
...
int *iptr = (int*) malloc(sizeof(*iptr));
As with C, you could use sizeof(int)
if you prefer, rather than sizeof(*iptr)
.
Note however the (theoretical) need for the namespace if you use cstdlib
. As Neil says, pretty much any implementation of <cstdlib>
will put malloc
in the global namespace, but this isn't guaranteed by the standard.
Also the (genuine) need for a cast, since C++ lacks C's automatic conversion of void*
to other pointer types. You could use a static_cast
rather than a C-style cast, but personally in this case I don't see the point.
As everybody says, there's little good reason to use malloc
in C++. Interfacing with C code which requires a malloced pointer (because the C code will free it) is one good reason, but you can get into trouble even there if the two bits of code are in different dlls.
Question 2: "How do I allocate memory in C++?"
Normally you would do this:
int *iptr = new int;
int *intarrayptr = new int[23];
delete iptr;
delete[] intarrayptr;
Or for raw data to be used for some nefarious purpose that you can't represent as a C++ object / array, do this:
unsigned char *twentythreebytes = (unsigned char*) ::operator new(23);
::operator delete(twentythreebytes);
However, allocating memory off the heap like this is also quite rare in (well-designed, high-level) C++ code. Prefer automatic or member variables, and standard containers, where possible:
#include <vector>
...
std::vector<int> intarray(23);
// no need to delete: the array will be destroyed when it goes out of scope.
The new
and delete
operators are the preferred C++ alternatives to malloc()
and free()
, because they are aware and capable of invoking the constructors and destructors of classes, in addition to allocation and deallocation of memory:
Foo* foo_ptr = new Foo();
delete foo_ptr; // this calls Foo::~Foo(), the destructor
The only time I have ever used malloc
and free
in C++ is to implement dummy-versions of the memory management routines:
#include <cstdlib>
#include <stdexcept>
void* operator new(size_t number_of_bytes) throw (std::bad_alloc)
{
void* p = malloc(number_of_bytes);
if (p == 0) throw std::bad_alloc();
std::cout << "allocated non-array memory @ " << p << '\n';
return p;
}
void* operator new[](size_t number_of_bytes) throw (std::bad_alloc)
{
void* p = malloc(number_of_bytes);
if (p == 0) throw std::bad_alloc();
std::cout << "allocated array memory @ " << p << '\n';
return p;
}
void operator delete(void* p) throw ()
{
if (p == 0) return;
std::cout << "releasing non-array memory @ " << p << '\n';
free(p);
}
void operator delete[](void* p) throw ()
{
if (p == 0) return;
std::cout << "releasing array memory @ " << p << '\n';
free(p);
}
Using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete.
Another major reason is for using new & delete : they are much more portable while malloc/calloc.. are not(Also new calls constructors and delete calls destructors while malloc and free do not). You will normally never get a problem using new & delete also on different platforms with different processers, because they encapsulate all calls to the native malloc functions safely.
The new operator can be used to create objects of any type. It takes the following general form-
pointer-variable = new data-type;
精彩评论