

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Both malloc() and calloc() are functions used to allocate dynamic memory during program execution. However, they differ in how they allocate and initialize this memory.
Feature malloc() calloc() Memory allocation Allocates uninitialized memory Allocates memory and initializes it to zero Syntax malloc(size_t size) calloc(size_t num, size_t size) Initialization No (contains garbage data) Yes (all bits set to zero) Typical use case When you plan to overwrite all data immediately When you want allocated memory to start with zero values
Example 1: Using malloc() #include #include int main() { int* arr = (int*) malloc(3 * sizeof(int)); if (arr == NULL) { printf("Memory allocation failed.\n"); return 1; } // Values are garbage initially printf("Values before initialization: %d %d %d\n", arr[0], arr[1], arr[2]); // Initialize the array arr[0] = 10; arr[1] = 20; arr[2] = 30; printf("Values after initialization: %d %d %d\n", arr[0], arr[1],