Difference between malloc and realloc

Introduction

Memory allocation is a significant part of programming, particularly in dialects like C where manual memory on the board is fundamental. In C two basic capabilities for dynamic memory designation are malloc and realloc. The two capabilities assume a vital part in overseeing memory during runtime, yet they fill various needs. This article aims to investigate the complicated contrasts between malloc and realloc, revealing insight into their functionalities, use cases, and suggestions for viable memory for executives.

Memory allocation in C:

Before digging into the particulars of malloc and realloc, understanding the idea of dynamic memory allotment in C is vital. In contrast to static memory designation, where the size of not entirely set in stone at gather time, dynamic memory distribution permits a program to dispense memory during runtime. This adaptability is pivotal while managing information designs of changing sizes or when the specific memory prerequisites are not known ahead of time.

What is malloc?

malloc is a capability in the C programming language that means "memory designation." It is important for the standard C library and is utilized for the dynamic memory portion during the execution of a program.

Difference between malloc and realloc

Here is a concise outline of how malloc functions

Reason: malloc is utilized to distribute a predetermined measure of memory during runtime. It permits the program to demand memory depending on the situation, as opposed to depending exclusively on fixed-size clusters.

Syntax

Arguments:

size: how much memory to distribute, determined by bytes.

Return Value:

  • If the memory portion is effective, malloc returns a pointer to the start of the distributed block of memory.
  • If the portion comes up short (because of lacking memory, for instance), malloc brings Invalid back.

Example

In this model, malloc is utilized to designate memory for a variety of 5 whole numbers. The sizeof(int) is utilized to guarantee that the right measure of memory is allotted given the size of a number.

Memory Initialization:

The memory designated by malloc is uninitialized, significance of its substance is capricious. The developer must introduce the memory on a case-by-case basis.

Memory Deallocation:

In the wake of utilizing the designated memory, it's essential to free it utilizing the free capability to forestall memory spills.

free(array);

  • malloc is essential for overseeing dynamic memory in C projects, empowering more adaptable and proficient memory utilization contrasted with static memory distribution.

What is realloc?

realloc is a capability in the C programming language that means "reallocation." It is essential for the standard C library and is utilized for resizing a formerly designated block of memory during runtime. It takes into account the more adaptable memory of the executives, especially when the size of the information structure necessities to powerfully change.

Difference between malloc and realloc

Here is a short outline of how realloc functions

Reason: Realloc is utilized to change the size of a globally designated block of memory. It tends to increment or decrease the size of the block.

Syntax

ptr: A pointer to the recently designated memory block that should be resized.

size: The new size of the memory block, determined in bytes.

Return Value:

  • If the redistribution is effective, realloc returns a pointer to the start of the resized (or recently dispensed) memory block.
  • If the portion comes up short (because of needing more memory, for instance), malloc brings Invalid back.

Example

Memory Content Preservation

  • If the block's size is expanded, the substance of the current block is safeguarded up to the base of the old and new sizes.
  • On the off chance that the size is diminished, the overabundance of memory toward the end is liberated.

Memory Initialization

  • Like malloc, the recently distributed or resized memory is uninitialized. The software engineer must instate the memory on a case-by-case basis.

Memory Deallocation

  • After utilizing the resized or recently designated memory, it's pivotal to free it utilizing the free capability when it's not generally required.
  • realloc is an amazing asset for overseeing dynamic memory in C, considering productive changes following the size of memory blocks during program execution.

Differences

mallocrealloc
Initial Allocation vs. ResizingThis capability is utilized for the underlying distribution of memory. It creates another memory block of a predefined size, and the block's substance is uninitialized.They are utilized for resizing a current memory block. Depending on the new size boundary, the block can be extended or contracted.
Function Signatures:void* malloc(size_t size);
Takes a single argument, the size (in bytes) of the memory block to be allocated.
Returns a void pointer (void*) pointing to the beginning of the allocated block.
void* realloc(void* ptr, size_t size);
Takes two arguments - a pointer to the existing memory block (ptr) and the new size (in bytes) of the block.
Returns a void pointer pointing to the beginning of the resized block.
Input Parameters:Takes only the size of the memory to be allocated.Takes both a pointer to the existing block of memory and the new size as parameters.
Handling Existing DataAllocates a new block of memory without preserving the data in the previously allocated blocks. The content of the new block is uninitialized.Preserves the data from the existing block while resizing. If the new block is larger, the additional space is uninitialized.
Return Value:Returns a pointer to the beginning of the newly allocated memory block. If the allocation fails, it returns a null pointer.Returns a pointer to the beginning of the resized memory block. This pointer may or may not be the same as the original pointer. If the reallocation fails, it returns a null pointer and leaves the original block unchanged.
Null Pointer HandlingIf it cannot allocate the requested memory, it returns a null pointer.If it cannot resize the memory block, it returns a null pointer, and the original block remains unchanged.
Usage for Dynamic ArraysTypically used when creating a dynamic array or allocating memory for the first time.Commonly used when the size of a dynamic array needs to be adjusted during runtime. It allows for efficient resizing without the need to create a new array and copy data.
Explicit Freeing of MemoryTo prevent memory leaks, memory allocated using malloc should be explicitly freed using the free function when it is no longer needed.Memory reallocated using realloc may involve freeing the original block. The pointer returned by realloc can be used directly without the need for a separate free call for the original block.
Handling Reallocation FailuresIf memory allocation fails, it returns a null pointer.If reallocation fails, it returns a null pointer, and the original block remains unchanged. It allows for graceful error handling without losing the original data.
Performance ConsiderationsGenerally more efficient for allocating memory when the size is known in advance since it avoids unnecessary copying of data.It may involve copying data if the memory block needs to be moved to a different location, impacting performance for large blocks. However, it provides the advantage of resizing existing memory without manual memory management.

Implementation

Output:

Difference between malloc and realloc

Explanation:

  1. The program starts by allocating memory for an array of integers (dynamicArray) using malloc. The size of the initial array is set to 5.
  2. The program checks if the memory allocation was successful. If not, it prints an error message and exits with an error code.
  3. The program initializes and prints the initial array elements (multiples of 2) to demonstrate the content of the dynamically allocated array.
  4. The program then uses realloc to resize the array to a new size of 10.
  5. Similar to the initial allocation, the program checks if the memory reallocation was successful. If not, it prints an error message, frees the memory allocated by malloc, and exits with an error code.
  6. The program initializes and prints the new elements in the resized array, demonstrating how realloc preserved the existing data.
  7. Finally, the program frees the memory allocated by realloc using the free function.





Latest Courses