Newbie confusion - when must I free the memory

Discussion in 'C Programming' started by Alf, May 16, 2004.

  1. Alf

    Alf Guest

    Hi, I've got myself confused as to when I should delete memory and when the
    system will do so automatically.

    I'm using strtod() in a function

    char *stopstring;
    double x = strtod( txtBuffer,&stopstring );

    Must I free any memory allocated to stopstring or is it done automatically
    when I exist the function?

    I am a bit confused as I have seen this microsoft example (using c++)

    char* lpszText2 = _com_util::ConvertBSTRToString(bstrTag);

    which explicitely deletes the memory at the end of the function, thus:

    delete[] lpszText2;

    Similarly say any function returns a char *.

    Say,
    char *p;

    p=charpreturned();

    should I free the memory in the calling routine?

    Thanks
     
    Alf, May 16, 2004
    #1
    1. Advertising

  2. Alf

    -berlin.de Guest

    Alf <> wrote:

    > Hi, I've got myself confused as to when I should delete memory and when the
    > system will do so automatically.


    > I'm using strtod() in a function


    > char *stopstring;
    > double x = strtod( txtBuffer,&stopstring );


    > Must I free any memory allocated to stopstring or is it done automatically
    > when I exist the function?


    You don't need to free 'stopstring', it points after call to some place
    in 'txtBuffer'. You only have to be careful not to use 'stopstring'
    anymore after you have free()ed the memory 'txtBuffer' is pointing to
    (if 'txtBuffer' has been pointing to allocated memory at all).

    > I am a bit confused as I have seen this microsoft example (using c++)


    > char* lpszText2 = _com_util::ConvertBSTRToString(bstrTag);


    > which explicitely deletes the memory at the end of the function, thus:


    > delete[] lpszText2;


    First, that's C++ and then it's some strange MS function, so I have
    no idea what it's supposed to do. And just by looking at that function
    call you can't tell if you have to deallocate memory associated with
    the returned pointer. You have to read the documentation. If you can't
    find out there you can't use the function savely.

    > Similarly say any function returns a char *.


    > Say,
    > char *p;


    > p=charpreturned();


    > should I free the memory in the calling routine?


    Again, that depends. The function may return a pointer to an allocated
    string, in which case you have to free() it sometime later, but it also
    could return a pointer to some static string, in which case calling
    free() on the pointer would be an horribe mistake. You have to read
    the documentation (or the source) foe the function to find out. There's
    no other way to know.
    Regards, Jen
    --
    \ Jens Thoms Toerring ___ -berlin.de
    \__________________________ http://www.toerring.de
     
    -berlin.de, May 16, 2004
    #2
    1. Advertising

  3. Alf

    Paul Emmons Guest

    On Sun, 16 May 2004 17:36:23 +0100, "Alf" <> wrote:

    > Similarly say any function returns a char *.
    >
    >Say,
    >char *p;
    >
    >p=charpreturned();
    >
    > should I free the memory in the calling routine?


    No-- unless you wrote charpreturned() and it used malloc(), or someone
    else wrote it and the documentation instructs you to use free() on the
    pointer returned.

    You should use free(p) only for memory obtained with p=malloc(). And
    the value of p should be the same.

    You can reserve a great deal of memory without using malloc(), and
    then all you need to free() is your mind from the issue. The space for
    variables (except static) declared in a function is automatically
    freed when the function returns; and static variable space
    is happily freed when the program exits.

    Getting space with malloc() is rather a last resort (which isn't to
    deny that it is needed in many situations).
     
    Paul Emmons, May 16, 2004
    #3
  4. Alf

    Malcolm Guest

    "Paul Emmons" <> wrote in message
    >
    > Getting space with malloc() is rather a last resort (which isn't to
    > deny that it is needed in many situations).
    >

    I think this is a bit misleading for new readers. Usually code written by
    newbies doesn't use malloc() enough, and instead uses buffers with arbitrary
    limits. Heavy use of malloc() is often a sign of a well-written and robust
    program.
     
    Malcolm, May 16, 2004
    #4
  5. Malcolm wrote:
    > "Paul Emmons" <> wrote in message
    >
    >>Getting space with malloc() is rather a last resort (which isn't to
    >>deny that it is needed in many situations).
    >>

    >
    > I think this is a bit misleading for new readers. Usually code written by
    > newbies doesn't use malloc() enough, and instead uses buffers with arbitrary
    > limits. Heavy use of malloc() is often a sign of a well-written and robust
    > program.
    >
    >


    I disagree. I've written and written code for many robust
    embedded systems that did not use any malloc. Dynamic memory
    is evil for systems that don't have much to spare. Fragmentation
    is disasterous for saftey critical systems.

    --
    Thomas Matthews

    C++ newsgroup welcome message:
    http://www.slack.net/~shiva/welcome.txt
    C++ Faq: http://www.parashift.com/c -faq-lite
    C Faq: http://www.eskimo.com/~scs/c-faq/top.html
    alt.comp.lang.learn.c-c++ faq:
    http://www.raos.demon.uk/acllc-c /faq.html
    Other sites:
    http://www.josuttis.com -- C++ STL Library book
    http://www.sgi.com/tech/stl -- Standard Template Library
     
    Thomas Matthews, May 17, 2004
    #5
  6. Alf

    Paul Emmons Guest

    On Sun, 16 May 2004 23:23:38 +0100, "Malcolm"
    <> wrote:

    >Heavy use of malloc() is often a sign of a well-written and robust
    >program.
    >

    It's also the cause of memory leaks, which are the bane even of some
    commercially available packages. We don't get to see the source code
    for these, but I wonder whether a pendulum has swung too far.

    Malloc might need to be used heavily, but not indiscriminately. The
    OP sounded as though the writer didn't realize that we don't need to
    use malloc() and free() constantly. My apologies if I misunderstood.
     
    Paul Emmons, May 17, 2004
    #6
  7. Alf

    Paul Emmons Guest

    I'm glad to see that someone agrees with me.

    When I wrote "you can reserve a great deal of memory without using
    malloc()", I didn't mean "go ahead and be a hog." I meant that
    relatively few situations need malloc().

    We might profit from a general discussion of this issue.

    A conceivable rule of thumb might be,
    "If you need an array of an uncertain number of elements,
    estimate the maximum reasonable number and double it."

    Considerations that might modify this rule might be:

    - What will be the results of underestimating?
    - What is the size of one element? (The greater the size, the better
    it might be to make it a linked list and use malloc()).
    - What is the lifetime of the array? (Longer life=unkinder to the
    environment to own unused memory).
    - What is the anticipated operating system and environment?

    There's always an overhead to using malloc(). An element obtained
    from malloc uses more memory overall. It takes time to allocate and
    free. It might make your program larger and slower. Algorithms and
    subsystems might be simplified by assuming that a resource is
    infinite, but it never really is.

    I do use malloc(), but not often and not without thinking twice. So
    it might not be fair to its enthusiasts, but let's hear a sort of
    manifesto:

    When do you use it, and why?
     
    Paul Emmons, May 17, 2004
    #7
  8. "Alf" <> wrote in message
    news:40a79877$0$20516$...
    >
    > Hi, I've got myself confused as to when I should delete memory and when

    the
    > system will do so automatically.


    As a general rule, if you call malloc() and it succeeds then you need to
    call free() after you're done with that memory.

    If the memory is automatically allocated for you, for example as a char
    array or string literal, you can't free() it.

    > I'm using strtod() in a function
    >
    > char *stopstring;
    > double x = strtod( txtBuffer,&stopstring );
    >
    > Must I free any memory allocated to stopstring or is it done automatically
    > when I exist the function?


    Memory is never allocated to stopstring -- it's just a pointer into
    txtBuffer. Since you didn't include the allocation (and possible freeing)
    of txtBuffer, we can't comment on if that's done correctly.

    > I am a bit confused as I have seen this microsoft example (using c++)


    Off-topic on c.l.c.

    > Similarly say any function returns a char *.
    >
    > Say,
    > char *p;
    >
    > p=charpreturned();
    >
    > should I free the memory in the calling routine?


    That depends. Sometimes the returned char* will point into a static char
    array maintained by the function you're calling, in which case you can't
    free() it. Other times, the function is calling malloc() behind the scenes
    and you therefore need a matching free(). The documentation for the
    specific function you're calling should specify which convention it's using.

    S

    --
    Stephen Sprunk "Stupid people surround themselves with smart
    CCIE #3723 people. Smart people surround themselves with
    K5SSS smart people who disagree with them." --Aaron Sorkin
     
    Stephen Sprunk, May 17, 2004
    #8
  9. On Sun, 16 May 2004 21:37:27 -0400, in comp.lang.c , Paul Emmons
    <> wrote:

    >When I wrote "you can reserve a great deal of memory without using
    >malloc()", I didn't mean "go ahead and be a hog." I meant that
    >relatively few situations need malloc().


    >A conceivable rule of thumb might be,
    >"If you need an array of an uncertain number of elements,
    >estimate the maximum reasonable number and double it."


    And then explain to your boss why the software crashes when your database
    grows larger and the crash requires rewriting in order to fix the bug,
    instead of tweaking of some config parameter, or even better not crashing
    at all.

    This is a /bad/ rule of thumb. A better rule of thumb is "never try to be
    idiot-proof. The universe has a 15Bn year headstart on you in designing
    better idiots"

    >Considerations that might modify this rule might be:

    ...
    >- What is the size of one element? (The greater the size, the better
    >it might be to make it a linked list and use malloc()).


    Why?

    >There's always an overhead to using malloc(). An element obtained
    >from malloc uses more memory overall.


    This might be true on your system, but there's nothing that makes it
    axiomatic.

    >It takes time to allocate and free.


    nor this. Consider that automatic storage also has to be allocated, and
    there's no reason why this shold be any slower or faster than malloc.

    >It might make your program larger and slower.


    And even if both were true, it might be even slower and less friendly to
    grab a huge chunk of memory at startup via a global variable.

    >When do you use it, and why?


    Whenever I need memory of an amount I can't define during the design of the
    software. If I need to store the letters of the roman alphabet, then an
    array of 27 chars is acceptable to me. If I need to read data from a file
    and process it, then malloc is way more sensible.
    --
    Mark McIntyre
    CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
    CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>


    ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
    http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
    ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
     
    Mark McIntyre, May 17, 2004
    #9
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ning
    Replies:
    4
    Views:
    721
    Dan Pop
    Sep 26, 2003
  2. Brad Clements
    Replies:
    1
    Views:
    987
    Roeland Rengelink
    Jun 23, 2004
  3. Cameron Laird
    Replies:
    6
    Views:
    1,129
    Cameron Laird
    Aug 18, 2006
  4. NeoGeoSNK
    Replies:
    25
    Views:
    973
    NeoGeoSNK
    Nov 24, 2006
  5. Panduranga Chary

    How memory function free() knows how much memory to free.

    Panduranga Chary, Dec 27, 2007, in forum: C Programming
    Replies:
    2
    Views:
    444
    Keith Thompson
    Dec 27, 2007
Loading...

Share This Page