Apply for Zend Framework Certification Training

c




< Memory Leaks - Understanding and Avoiding Some facts on pointers in c >



Difference between malloc() and calloc()
 
1. Basic Difference
Feature malloc() calloc()
Full Form Memory Allocation Contiguous Allocation
Parameters 1 (total size in bytes) 2 (number of elements, size of each)
Initialization ? Not initialized (garbage values) ? Initialized to 0
Speed Faster Slightly slower
Syntax malloc(size) calloc(n, size)
 
2. Syntax
ptr = (type*) malloc(size_in_bytes);
ptr = (type*) calloc(number_of_elements, size_of_each);
 
3. Example of malloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
    int *arr;
    int i;
    arr = (int*) malloc(5 * sizeof(int));
    printf("Values using malloc:\n");
    for(i = 0; i < 5; i++) {
        printf("%d ", arr[i]);  // garbage values
    }
    free(arr);
    return 0;
}
Effect:
Memory is allocated but not initialized
Output shows random (garbage) values
 
4. Example of calloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
    int *arr;
    int i;
    arr = (int*) calloc(5, sizeof(int));
    printf("Values using calloc:\n");
    for(i = 0; i < 5; i++) {
        printf("%d ", arr[i]);  // all zeros
    }
    free(arr);
    return 0;
}
Effect:
Memory is allocated and initialized to 0
Output shows 0 0 0 0 0
 
5. Key Concept (Important for Exams)
malloc() → gives unpredictable values
calloc() → gives clean memory (all zeros)
 
6. Real-Life Example
malloc() 
Like renting a room without cleaning → dust and mess already there
calloc() 
Like renting a room that is fully cleaned and ready to use
 
7. When to Use
Use malloc() when:
You will assign values manually
Need faster allocation
Use calloc() when:
You need default zero values
Working with arrays where initial value matters
 
8. Important Note
Always free memory:
free(ptr);

< Memory Leaks - Understanding and Avoiding Some facts on pointers in c >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top