malloc, calloc from the FAQ

This is a discussion on malloc, calloc from the FAQ within the C Programming forums, part of the General Programming Boards category; Hi Guys, I read the following in the FAQ: Originally Posted by FAQ malloc leaves the block of memory uninitialized, ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    84

    malloc, calloc from the FAQ

    Hi Guys,

    I read the following in the FAQ:
    Quote Originally Posted by FAQ
    malloc leaves the block of memory uninitialized, but calloc zero fills the memory. This does not mean that

    p = calloc ( 1, sizeof ( int * ) );

    will result in a pointer to int with a value of NULL. Zero filled memory does not mean that the memory is filled with the data type's equivalent of 0, so this zero fill cannot be relied on except with integral values such as int or char. Pointers and floating point may use a different representation for 0 than all bits zero.
    Please tell me if I got it right:

    1.
    I CAN'T rely on calloc to Zero fill memory with floating points??
    Code:
                    float *pArr;
    	int i;
    	
    	for (i=0;i<10;++i)
    	{
    		pArr=calloc(sizeof(*pArr),10);
    		printf("%f\n",pArr[i]);
    	}
    The result I get is 0.

    2.
    I CAN'T rely on calloc to Zero fill memory where pointers point to??
    Code:
                    float *pArr[10];
    	int i;
    	
    	for (i=0;i<10;++i)
    	{
    		pArr[i]=calloc(sizeof(float *),10);
    		printf("%f\n",*pArr[i]);
    	}
    Again the result is 0.

    3. CAN I rely that calloc will Zero fill memory for int , char ,long??

    Many thanks for your help

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Before relying on a FAQ, why not simply calloc a few arrays of different types and see for yourself, EXACTLY how YOUR compiler, handles the matter.

    Would it actually take more than 60 seconds to find the answer? Maybe.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    84
    Quote Originally Posted by Adak View Post
    Before relying on a FAQ, why not simply calloc a few arrays of different types and see for yourself, EXACTLY how YOUR compiler, handles the matter.

    Would it actually take more than 60 seconds to find the answer? Maybe.
    Thats what I did.
    My results are different than desribed on the FAQ (as I mantioned in my preview post).
    I assume that who ever wrote it know what ihe s talking about, and because I WANT my code to be portable and NOT compiler dependent, I'm looking for someone to make the last bit of the FAQ clear for me. (me bad english).

    Thanks

    EDIT: Why not rely on the FAQ?? it contain great portable information.

  4. #4
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,525
    First of all, you're swapping the arguments to calloc. Review the prototype and you will see that the number of objects is the first argument, and the size of the object is the second.

    For types like char and long, calloc will initialize to zero properly. The caveat with calloc is that it simply sets all bits in a block to zero, like you might with a call to memset. This is not sufficient to give all types a zero state.

    I'm not really going to give a complete overview of the types that won't be initialized properly by calloc, but much of it has to do with the bit representation of zero. For instance, zero in a double is definitely not all bits zero, because in most implementations of the type you've got sign bits and the mantissa, etc.

    The safest way to turn anything you allocate to zero state is to malloc and then assign zero, or NULL, or something appropriate for that type.
    Last edited by whiteflags; 01-19-2008 at 12:45 PM.

  5. #5
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    For instance, zero in a double is definitely not all bits zero, because in most implementations of the type you've got sign bits and the mantissa, etc.
    Even purged of errors the OP's test program still prints zeros for floats (doubles).
    That does seem weird since I'm pretty sure the exponent on my machine is "excess-N" as opposed to 2's complement, so a 0 should be the most negative exponent.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        double *p;
        int n = 10;
    
        p = calloc(n, sizeof(double));
    	
        while (n--)
            printf( "&#37;.17e\n", *p++); /* double has about 16 decimals */
    }

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    In IEEE floats and doubles, there is a "bias" in the exponent; however, it also assumes an implicit "1" in front of the binary point (since in "scientific" notation, there is always one nonzero digit in front of the decimal point, and in binary there is only one nonzero digit). However, if the exponent is zero, that implicit "1" is not assumed (this is called "denormalized"). So the only way to get zero is all bits zero.

  7. #7
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,424
    Even purged of errors the OP's test program still prints zeros for floats (doubles).
    How many compilers and OSes have you tested?
    FAQ just says that this code is not portable - it means - there are compilers where the result will be different.
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  8. #8
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,158
    The answers:

    1: No, you can't.
    2: No, you can't.
    3. Yes, you can.

  9. #9
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,335
    Another FAQ which says the same thing.
    http://c-faq.com/malloc/calloc.html

    > Before relying on a FAQ, why not simply calloc a few arrays of different types and
    > see for yourself, EXACTLY how YOUR compiler, handles the matter.
    But that isn't going to tell you anything about how portable an action is going to be.
    Reading the ISO standard is, observations of one specific implementation isn't.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  10. #10
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,261
    Quote Originally Posted by tabstop View Post
    In IEEE floats and doubles, there is a "bias" in the exponent; however, it also assumes an implicit "1" in front of the binary point (since in "scientific" notation, there is always one nonzero digit in front of the decimal point, and in binary there is only one nonzero digit). However, if the exponent is zero, that implicit "1" is not assumed (this is called "denormalized"). So the only way to get zero is all bits zero.
    tabstop is actually right. Setting all bits to zero does happen to result in a double value of zero, precisely for the reasons stated. Zero for the exponent means denormalised, and the value of the mantissa indicates an actual value of zero. The sign bit being zero simply shows that the value is 0 and not -0. (though those two actually compare equal anyway).
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    If you LIMIT your software to run on systems where "all bits zero" mean NULL and that float/double have a format where if all bits are zero, it means zero, then you should be OK. IEEE-conformant floating point formats would satisfy this requirement. As to NULL pointers and their value, you'd have to look at the individual system definition.

    For "ordinary" systems, the above would hold true: Windows and Linux on x86 for example will work just fine.

    But it's not guaranteed.

    And there's a saying "If you're going to break the rules, you should know the rule you are breaking" - meaning that you are AWARE of what you are doing, rather than just doing it out of blind ignorance.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Malloc & Calloc difference in terms of memory allocated
    By swapnaoe in forum C Programming
    Replies: 2
    Last Post: 04-19-2007, 12:57 AM
  2. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  3. difference between calloc and malloc
    By saravanan_ts in forum C Programming
    Replies: 4
    Last Post: 07-28-2003, 06:13 AM
  4. Calloc vs. Malloc
    By SavesTheDay in forum C Programming
    Replies: 3
    Last Post: 02-18-2002, 02:56 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21