Thread: Best way to allocate a struct pointer: malloc or calloc?

  1. #1
    Registered User Joelito's Avatar
    Join Date
    Mar 2005
    Tijuana, BC, México

    Exclamation Best way to allocate a struct pointer: malloc or calloc?

    in C++ I can use:
    PHP Code:
    someStruct *pSs = new someStruct
    But in C, which:
    PHP Code:
    someStruct *pSs = (someStruct*)malloc(sizeof(someStruct)); 
    PHP Code:
    someStruct *pSs = (someStruct*)calloc(0sizeof(someStruct)); 
    I'm confused because I see people using both :\
    Last edited by Joelito; 03-27-2007 at 06:46 PM.
    * PC: Intel Core 2 DUO E6550 @ 2.33 GHz with 2 GB RAM: Archlinux-i686 with xfce4.
    * Laptop: Intel Core 2 DUO T6600 @ 2.20 GHz with 4 GB RAM: Archlinux-x86-64 with xfce4.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Either one works. They both do the same thing in that they allocate a block of memory. The difference is that calloc sets the values to zero, and malloc does not. You will still likely have to go and initialize your pointers manually even if you use calloc however, because a zero value does not necessarily mean NULL.

    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Sep 2006
    You don't have to cast malloc(), calloc(), or realloc() in C:

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. seg fault with nested struct from pointer
    By seaking1 in forum C Programming
    Replies: 4
    Last Post: 05-01-2009, 03:09 PM
  2. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  3. Replies: 10
    Last Post: 05-18-2006, 11:23 PM
  4. Function validation.
    By Fhl in forum C Programming
    Replies: 10
    Last Post: 02-22-2006, 08:18 AM
  5. pointer to a struct
    By ramdal in forum C Programming
    Replies: 13
    Last Post: 12-15-2005, 09:01 AM