malloc

From Cppwiki

(Redirected from free)
Jump to: navigation, search

malloc and free are standard library functions used to allocate and deallocate chunks of raw memory. They were inherited from C, and in C++ new and delete are usually preferable, but some reasons still exist to use malloc and free, such as interaction with C libraries.

void *malloc(std::size_t n) 
allocates a block of n bytes of memory. The storage returned is aligned suitably to hold an object of any type, but no constructors are called (because malloc does not know about the type being allocated). If an error occurs, malloc returns NULL. (malloc can also return NULL if a zero-sized allocation is attempted; this does not indicate failure).
void *realloc(void *p, std::size_t n) 
resizes, and possibly moves, the memory block p, which must be either NULL or a pointer returned from a previous call to malloc or realloc, to be at least n bytes large. the new location of the memory (which may be unchanged) is returned. if p is NULL, realloc behaves as malloc(n). even if the memory is moved, the start of the block (up to the size of the previous allocation) is preserved. however, realloc does not call copy constructors, so it is not safe to use with C++ objects.
void free(void *p); 
deallocate the block p, which must have been returned from a previous call to malloc or realloc. If p is NULL, the call has no effect.

Neither malloc nor realloc guarantee the contents of newly allocate memory (in particular, it is not zeroed).

A common idiom when using malloc, to prevent errors, is to allocate using sizeof(*dst):

 struct T *p = malloc(sizeof(*p));

This prevents accidental allocation of the wrong size block, which can occur if malloc(sizeof(struct T)) was used.

Personal tools