What is the dfference between realloc() and free()?

Recommended Answers

All 5 Replies

realloc

void* realloc (void* ptr, size_t size);

Reallocate memory block
Changes the size of the memory block pointed to by ptr.

free

void free (void* ptr);

Deallocate memory block
A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.

What is the dfference between realloc() and free()?

free() performs a task that is a subset of realloc(). Here's what realloc() does:

  • realloc(p, n): Changes the size of the block pointed to by p and returns p. If the size of that block cannot be changed, allocates a new block of n bytes, copies the contents of p, and then returns that new block.
  • realloc(NULL, n): Allocates a new block of n bytes and returns it. Functionally identical to malloc(n).
  • realloc(p, 0): Releases the memory allocated by p and returns NULL. Functionally identical to free(p).

If you're really interested, here's a sample implementation of realloc() and free(). That's a working implementation of stdlib.h, so you can also look at malloc() and the system-specific back end of each.

Just be aware that you should not use malloc(), realloc() or free() in c++ programs because they do not call c++ class constructors or destructors. Instead, use new and delete. Unfortunately there is no c++ equivalent of realloc().

free() is a macro which is used to deallocate memory. When we need more memory realoc() reallocate memory according to given size.

free() is a macro which is used to deallocate memory.

free() is not a macro, it's a function.

When we need more memory realoc() reallocate memory according to given size.

While not technically wrong, there's so much missing that this answer borders on useless. It's essentually a tautology. You're saying that realloc() reallocates memory, which is obvious, redundant, and essentially defines realloc() in terms of itself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.