Newbie confusion - when must I free the memory

A

Alf

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
 
J

Jens.Toerring

Alf said:
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;

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
 
P

Paul Emmons

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

Malcolm

Paul Emmons said:
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.
 
T

Thomas Matthews

Malcolm said:
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
 
P

Paul Emmons

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

Paul Emmons

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?
 
S

Stephen Sprunk

Alf said:
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
 
M

Mark McIntyre

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top