Forum

Notifications
Clear all

Learn Calloc()

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

The calloc() function in C stands for contiguous allocation, and it’s used to allocate memory dynamically—just like malloc()—but with a key difference: it initializes all allocated bytes to zero.


🧠 What calloc() Does

  • Allocates memory for an array of elements.
  • Initializes all bytes in the allocated memory to zero.
  • Returns a void* pointer to the beginning of the block.
  • If allocation fails, it returns NULL.

📦 Syntax

void* calloc(size_t num_items, size_t size_per_item);
  • num_items: Number of elements to allocate.
  • size_per_item: Size of each element in bytes.

🧪 Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int *)calloc(5, sizeof(int));  // Allocates space for 5 integers

    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);  // All values will be 0
    }

    free(arr);  // Always free allocated memory
    return 0;
}

🆚 malloc() vs calloc()

Feature malloc() calloc()
Initialization Uninitialized (garbage values) Zero-initialized
Parameters One: total size in bytes Two: number of elements & size
Performance Slightly faster Slightly slower due to zeroing

🛡️ Security Implications

  • Zero-initialization helps prevent information leakage from leftover memory.
  • Still vulnerable to buffer overflows and use-after-free if misused.

You can explore more examples and technical details on W3Schools or TutorialsPoint.

 


   
Quote
Share: