What is the difference between malloc() and calloc() memory allocation in C

1 Answer

0 votes
// Both allocates dynamic memory on the heap. 
// The difference: calloc fills the allocated memory with 0’s.

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

int main(void)
{
    // The pointer *s1 allocated on the stack
    // The dynamic memory is allocated on the heap
    char *s1 = (char *)malloc(13 * sizeof(char));
   
    strcpy(s1, "c c++");
    printf("s1 = %s\n", s1);
    free(s1);
    
    // The pointer *s2 allocated on the stack
    // The dynamic memory is allocated on the heap
    char *s2 = (char *)malloc(13 * sizeof(char));
   
    strcpy(s2, "c c++");
    printf("s2 = %s\n", s2);
    free(s2);

    return 0;
}

  
/*
run:
    
s1 = c c++
s2 = c c++

*/

 



answered Jun 20, 2017 by avibootz
...