Let’s create a table summarizing the key differences between malloc()
and calloc()
functions in C:
Aspect | malloc() | calloc() |
---|---|---|
Syntax | void* malloc(size_t size); | void* calloc(size_t num_elements, size_t element_size); |
Memory Initialization | Uninitialized (contains garbage values) | Initialized to zero (all bytes are set to 0) |
Initialization Overhead | None | Slightly slower due to zero-initialization |
Usage | Suitable when memory content doesn’t matter | Suitable when initializing memory to zero is necessary |
Example | int* ptr = (int*)malloc(5 * sizeof(int)); | int* ptr = (int*)calloc(5, sizeof(int)); |
Remember to handle memory allocation errors and free the allocated memory using free()
after you’re done using it to avoid memory leaks.