Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,847 questions

51,768 answers

573 users

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

Related questions

...