Thread: realoc, calloc

  1. #31
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by brewbuck View Post
    But assuming that freshly-allocated memory will contain all zeros is not correct (I'm not saying that's what you're saying, matsp)
    I agree with that - first of all, there's no way to KNOW if the memory is "fresh" or "old and mouldy" when you ask for memory from malloc - or when you ask from the OS directly. It may use memory previously owned by this process or some such.

    The only way to "know" what's in memory recently allocated is if you use calloc or you fill it yourself. Anything else is "undefined".

    --
    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.

  2. #32
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Debug versions of malloc specifically set the memory to known "magic" numbers to assist with such things as
    - use before initialisation
    - use after free.

    If you see these magic numbers in the memory you allocated, you know you've messed up.

    But other than that, definitely assume it's junk to begin with.
    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.

  3. #33
    Registered User
    Join Date
    Oct 2007
    Posts
    242
    So you're saying that calloc is better than malloc and I should use calloc?

  4. #34
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    calloc is a waste of effort if the very next thing you're going to do is say call strcpy() or fgets() which will simply overwrite what is already there with a valid string.

    Most of the time, you'll be wanting to write the data you really want to the memory first, so just call malloc. On some occasions, having zeroed out memory is nice since it saves you a memset call.

    But I would regard blanket use of calloc by a programmer as showing signs of not knowing what they were doing. Especially where it is immediately obvious that the "zeroising" aspect was a complete waste of time.

    Even when calloc would have worked, I often end up with malloc + memset.

    Being over-reliant on it can be a trap, since there is no 'calloc' version of realloc(), which will always leave you with uninitialised memory in the extra space.
    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.

  5. #35
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by eXeCuTeR View Post
    So you're saying that calloc is better than malloc and I should use calloc?
    Is a screwdriver better than a spanner? No. You should use the RIGHT tool for the job. And whilst you can use a screwdriver (or spanner) to hammer in nails, a hammer is actually much better for it.

    What makes it hard is that there is no firm and fast rule. But if you don't immediately fill your malloc'd memory with something, then you probably should use calloc(). There's obviously nothing wrong with always using calloc() - it is better than getting it wrong the other way. But it will cause un-necessary memory writes, when you fill it with zeros only to immediately stuff something else on top of those zeros.

    --
    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.

  6. #36
    Registered User
    Join Date
    Oct 2007
    Posts
    242
    Finally got it

    2 Questions:
    1. What is memset?
    2. Why do I have (note the comment):
    Code:
    int *p, str;
    p = malloc(sizeof(int));
    strcpy(p, str); // Why do I have to do that? Salem mentioned that.
    // He also mentioned fgets - how do I do it with fgets?

  7. #37
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    You've really gotta start looking at what all these functions do in your manual pages.
    We're certainly not going to explain the entire standard C library to you one message at a time.
    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.

  8. #38
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You only do strcpy() if you want to copy a character string.

    You use fgets() to read a string from the console or a file.

    memset is a function that fills a set amount of memory with a the value of a byte - typically zero, but other values can be used.

    --
    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.

  9. #39
    Registered User
    Join Date
    Oct 2007
    Posts
    242
    Could you atleast explain me why strcpy(p, str)? why do I need to copy the allocated memory into str?

  10. #40
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by eXeCuTeR View Post
    Could you atleast explain me why strcpy(p, str)? why do I need to copy the allocated memory into str?
    Ehm, it's the other way around. strcpy(destination, source) - so copies from the second argumen TO the first one.

    --
    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.

  11. #41
    Registered User
    Join Date
    Oct 2007
    Posts
    242
    So why do I need to put str in p? what different does it make whether the string/w/e is on str or p?
    You answered it yesterday I guess, but I forgot ^^

  12. #42
    Devil™
    Join Date
    Oct 2007
    Location
    IIT-Kharagpur, India
    Posts
    104
    Quote Originally Posted by eXeCuTeR View Post
    So why do I need to put str in p? what different does it make whether the string/w/e is on str or p?
    You answered it yesterday I guess, but I forgot ^^
    hmm..
    sometimes if you want to change the string you dont have to go to every point and change it..
    if you have something like this

    Code:
    main()
    {
        char str[]="I am string1";
        printf("%s\n",str);
        
        //now lets play with string in some function
        strcpy(str,"I am string2");
        
        printf("%s\n",str);
    }
    /**************************************************************
    else the basic way will be
    str[0]= 'I';
    str[1]=' ';
    str[2]='a';
    str[3]='m';
    ...
    str[13]='2';
    all these lines of code can be done in one single call strcpy(str,"I am string2")
    ***************************************************************/
    C's Motto: who cares what it means? I just compile it!!

  13. #43
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by eXeCuTeR View Post
    Finally got it
    2. Why do I have (note the comment):
    Code:
    int *p, str;
    p = malloc(sizeof(int));
    strcpy(p, str); // Why do I have to do that? Salem mentioned that.
    // He also mentioned fgets - how do I do it with fgets?
    That last line of code is not right in many ways.
    First, you cannot sensibly use strcpy on integer pointers.
    Secondly, you've declared str as simply an int so it wont compile.
    Hopefully you would never use malloc for something of such a small fixed size either.
    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"

  14. #44
    Registered User
    Join Date
    Oct 2007
    Posts
    242
    Quote Originally Posted by gibsosmat View Post
    hmm..
    sometimes if you want to change the string you dont have to go to every point and change it..
    if you have something like this

    Code:
    main()
    {
        char str[]="I am string1";
        printf("%s\n",str);
        
        //now lets play with string in some function
        strcpy(str,"I am string2");
        
        printf("%s\n",str);
    }
    /**************************************************************
    else the basic way will be
    str[0]= 'I';
    str[1]=' ';
    str[2]='a';
    str[3]='m';
    ...
    str[13]='2';
    all these lines of code can be done in one single call strcpy(str,"I am string2")
    ***************************************************************/
    So I get it:
    If I have a string, I can add it another string by using strcpy.
    But how come you use \n on on 1 variable and the output does have 2 lines? This is the strange part.
    I'm having difficult time to explain, lol, sorry.

  15. #45
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Salem View Post
    But I would regard blanket use of calloc by a programmer as showing signs of not knowing what they were doing. Especially where it is immediately obvious that the "zeroising" aspect was a complete waste of time.
    Yeah. And those guys who insist on initializing their variables when they declare them? Buncha know-nothings! Better to leave everything a mystery until the last second.

    I mean who wants determinism in their software anyway? Who would want to give up the joy of tracking down a failure caused by random uninitialized data only once in a thousand executions? And maintainability? Pshaw I say! Best to leave a maze for the next guy who gets to work on your code. Job security and all that.

    Being over-reliant on it can be a trap, since there is no 'calloc' version of realloc(), which will always leave you with uninitialised memory in the extra space.
    Code:
    void *crealloc(void *mem, size_t oldsize, size_t newsize)
    {
        void *newmem = realloc(mem, newsize);
        if(newmem && newsize > oldsize)
            memset(newmem + oldsize, 0, newsize - oldsize);
        return newmem; 
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc, calloc from the FAQ
    By salvadoravi in forum C Programming
    Replies: 10
    Last Post: 01-21-2008, 03:29 AM
  2. Help with calloc and pointers to strings.
    By sweetarg in forum C Programming
    Replies: 1
    Last Post: 10-24-2005, 02:28 PM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. Why use calloc()?
    By dwks in forum C Programming
    Replies: 8
    Last Post: 07-20-2005, 08:22 AM
  5. difference between calloc and malloc
    By saravanan_ts in forum C Programming
    Replies: 4
    Last Post: 07-28-2003, 06:13 AM