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

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

    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)); 
    or
    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
    Posts
    14,826
    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.


    Quzah.
    Hope is the first step on the road to disappointment.

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

    http://faq.cprogramming.com/cgi-bin/...&id=1043284351

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