473,287 Members | 1,413 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

memory allocation and freeing memory

there are sometimes that I use third party libraries, I use some functions
that returns char * or structs, etc. sometimes the memory that is returned
by those libraries, when I try to free this memory whith the function free,
it brokes my application, and sometimes it's ok, why? how do I realize when
I have to free the memory that is allocated by third party libraries and
why sometimes I don't have to free this memory?

Thank you
Nov 14 '05 #1
11 2252
Rodrigo Dominguez wrote:
there are sometimes that I use third party libraries, I use some functions
that returns char * or structs, etc. sometimes the memory that is returned
by those libraries, when I try to free this memory whith the function free,
it brokes my application, and sometimes it's ok, why? how do I realize when
I have to free the memory that is allocated by third party libraries and
why sometimes I don't have to free this memory?


You need to read the documentation that came with the libraries. The
functions that allocate memory should either have cleanup functions
that do deallocation or specify how you should free the objects
yourself.

Robert Gamble

Nov 14 '05 #2
Rodrigo Dominguez wrote on 13/06/05 :
there are sometimes that I use third party libraries, I use some functions
that returns char * or structs, etc. sometimes the memory that is returned
by those libraries, when I try to free this memory whith the function free,
it brokes my application, and sometimes it's ok, why? how do I realize when
Don't do that. Read the manual and follow the instructions.
I have to free the memory that is allocated by third party libraries and
why sometimes I don't have to free this memory?


There are several ways to implement a function returning a pointer to
an object. Only the library documentation informs you about the proper
way of using the functions.

I personally tend to add a '_dyn' suffix to functions returning
something to be freed to make it self-documenting...

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"There are 10 types of people in the world today;
those that understand binary, and those that dont."

Nov 14 '05 #3
I personally tend to add a '_dyn' suffix to functions returning
something to be freed to make it self-documenting...


A good practice (I think, I'm not a guru): a function never
returns a block it has allocated. This means that the caller
never frees memory, and the callee always frees all its
allocated blocks before function returns. If the callee needs
to return a block, then the caller allocates it and pass it
as an argument. Maybe there are situations where it doesn't work ?

Nov 14 '05 #4
Jean-Claude Arbaut <je****************@laposte.net> writes:
I personally tend to add a '_dyn' suffix to functions returning
something to be freed to make it self-documenting...


A good practice (I think, I'm not a guru): a function never
returns a block it has allocated. This means that the caller
never frees memory, and the callee always frees all its
allocated blocks before function returns. If the callee needs
to return a block, then the caller allocates it and pass it
as an argument. Maybe there are situations where it doesn't work ?


That approach is often useful, but it requires the caller to decide
how big a block to allocate (and pass the actual size as another
argument). If the caller allocates too little memory, the call fails;
if the caller allocates too much, the extra space is wasted. Leaving
the allocation up to the function allows the function to allocate
exactly as much space as is needed. On the other hand, it means the
caller has the burden of freeing it.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #5


Jean-Claude Arbaut wrote:
I personally tend to add a '_dyn' suffix to functions returning
something to be freed to make it self-documenting...

A good practice (I think, I'm not a guru): a function never
returns a block it has allocated. This means that the caller
never frees memory, and the callee always frees all its
allocated blocks before function returns. If the callee needs
to return a block, then the caller allocates it and pass it
as an argument. Maybe there are situations where it doesn't work ?


An approach I've found useful is to write pairs of
functions: one function allocates and initializes memory
for a Whatever and returns a Whatever*, while the other
accepts a Whatever* argument and does whatever is needed
to "de-initialize" the Whatever, including releasing its
memory. The advantage is that the caller never needs to
the details of how a Whatever is built: how much memory
is needed, whether it's all in one chunk or is built from
several pieces linked together, and so on.

For example, consider fopen() and fclose(). As the
caller you do not need to know anything about what a `FILE'
looks like; all you care about is the `FILE*'. You do not
know whether the `FILE' is allocated dynamically or statically,
what extra buffers and such may be allocated along with it,
and so on -- all you need to know is that fopen() produces a
`FILE*', and that fopen() cleans it up when you're done.

The same pattern works well for "purely memory" constructs,
too. I've written a little expression evaluator that has
three (principal) functions in its interface: a compiler that
transforms the source expression into an "opaque" data type
that's allocated during compilation, an evaluator that takes
the opaque pointer and an array of user-supplied variable
values and returns the expression's value, and a destructor
that accepts the opaque pointer and discards the memory it
uses. The current version of the destructor is fairly simple:

void ExprDestroy(Expr *expr) {
free (expr);
}

.... but by packaging it where the caller can't see the details
I retain the freedom to change my mind about the way memory is
managed, and perhaps do something like

void ExprDestroy(Expr *expr) {
free (expr->constants);
free (expr->bytecodes);
#ifndef NDEBUG
free (expr->debugging_info);
#endif
free (expr);
}

The caller never needs to know how things are done "behind the
curtain."

--
Er*********@sun.com

Nov 14 '05 #6

Le 13/06/2005 23:22, dans ln************@nuthaus.mib.org, «*Keith Thompson*»
<ks***@mib.org> a écrit*:
Jean-Claude Arbaut <je****************@laposte.net> writes:
I personally tend to add a '_dyn' suffix to functions returning
something to be freed to make it self-documenting...


A good practice (I think, I'm not a guru): a function never
returns a block it has allocated. This means that the caller
never frees memory, and the callee always frees all its
allocated blocks before function returns. If the callee needs
to return a block, then the caller allocates it and pass it
as an argument. Maybe there are situations where it doesn't work ?


That approach is often useful, but it requires the caller to decide
how big a block to allocate (and pass the actual size as another
argument). If the caller allocates too little memory, the call fails;
if the caller allocates too much, the extra space is wasted. Leaving
the allocation up to the function allows the function to allocate
exactly as much space as is needed. On the other hand, it means the
caller has the burden of freeing it.


Often the caller knows the size, or a bound may be known, and written in the
documentation. If the size is unknown a priori, maybe a first call can
compute a bound, and return the size. But there are cases when you simply
don't know the size before the computation, you're right.

In these situations, I would suggest a malloc/free approach: the allocating
function has a freeing counterpart. That's what is used in fopen/fclose I
suppose. And it allows modifications in the implementation: if you free all
struct members yourself, you depend on the struct "structure" :-)

Nov 14 '05 #7

Le 13/06/2005 23:22, dans d8**********@news1brm.Central.Sun.COM, «*Eric
Sosman*» <er*********@sun.com> a écrit*:


Jean-Claude Arbaut wrote:
I personally tend to add a '_dyn' suffix to functions returning
something to be freed to make it self-documenting...

A good practice (I think, I'm not a guru): a function never
returns a block it has allocated. This means that the caller
never frees memory, and the callee always frees all its
allocated blocks before function returns. If the callee needs
to return a block, then the caller allocates it and pass it
as an argument. Maybe there are situations where it doesn't work ?


An approach I've found useful is to write pairs of
functions: one function allocates and initializes memory
for a Whatever and returns a Whatever*, while the other
accepts a Whatever* argument and does whatever is needed
to "de-initialize" the Whatever, including releasing its
memory. The advantage is that the caller never needs to
the details of how a Whatever is built: how much memory
is needed, whether it's all in one chunk or is built from
several pieces linked together, and so on.

For example, consider fopen() and fclose(). As the
caller you do not need to know anything about what a `FILE'
looks like; all you care about is the `FILE*'. You do not
know whether the `FILE' is allocated dynamically or statically,
what extra buffers and such may be allocated along with it,
and so on -- all you need to know is that fopen() produces a
`FILE*', and that fopen() cleans it up when you're done.

The same pattern works well for "purely memory" constructs,
too. I've written a little expression evaluator that has
three (principal) functions in its interface: a compiler that
transforms the source expression into an "opaque" data type
that's allocated during compilation, an evaluator that takes
the opaque pointer and an array of user-supplied variable
values and returns the expression's value, and a destructor
that accepts the opaque pointer and discards the memory it
uses. The current version of the destructor is fairly simple:

void ExprDestroy(Expr *expr) {
free (expr);
}

... but by packaging it where the caller can't see the details

I retain the freedom to change my mind about the way memory is
managed, and perhaps do something like

void ExprDestroy(Expr *expr) {
free (expr->constants);
free (expr->bytecodes);
#ifndef NDEBUG
free (expr->debugging_info);
#endif
free (expr);
}

The caller never needs to know how things are done "behind the
curtain."


Ok, I was late in my answer ;-)

Indeed, I have already used this approach, I wonder why I didn't
Remember that earlier... Shame on me !

Nov 14 '05 #8
Jean-Claude Arbaut wrote on 13/06/05 :
A good practice (I think, I'm not a guru): a function never
returns a block it has allocated. This means that the caller
never frees memory, and the callee always frees all its
allocated blocks before function returns. If the callee needs
to return a block, then the caller allocates it and pass it
as an argument. Maybe there are situations where it doesn't work ?


How would malloc() work in such a world ?

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++

Nov 14 '05 #9

Le 14/06/2005 21:30, dans mn***********************@YOURBRAnoos.fr,
«*Emmanuel Delahaye*» <em***@YOURBRAnoos.fr> a écrit*:
Jean-Claude Arbaut wrote on 13/06/05 :
A good practice (I think, I'm not a guru): a function never
returns a block it has allocated. This means that the caller
never frees memory, and the callee always frees all its
allocated blocks before function returns. If the callee needs
to return a block, then the caller allocates it and pass it
as an argument. Maybe there are situations where it doesn't work ?
How would malloc() work in such a world ?


I'm not sure I understand your question. If you know how much space a
function will need, it isn't difficult to malloc and to pass it as a
parameter. No problem with malloc. But, maybe you mean that malloc
doesn't obey this precept ? That's right.

Anyway, Eric Sosman has already suggested a good solution for cases
when one doesn't know in advance how much space is needed.

Oh, and in case you hadn't noticed: what I describe is a method used
in many F77 programs to pass arrays. F77 cannot allocate memory, so
the usual trick is: create a big data chunk (a global variable), wide enough
for all your needs, merely a heap. Then treat this "heap" as a stack,
and pass variables in that stack to functions as needed (and maintain
stack state). It's the method used in PORT3 to emulate dynamic allocation.
Even in F90, there are programs that allocate memory at the beginning
of the program and use that trick afterwards, MT3D is an example.

Nov 14 '05 #10
Jean-Claude Arbaut wrote on 14/06/05 :
Oh, and in case you hadn't noticed: what I describe is a method used
in many F77 programs to pass arrays. F77 cannot allocate memory, so
the usual trick is: create a big data chunk (a global variable), wide enough
for all your needs, merely a heap. Then treat this "heap" as a stack,
and pass variables in that stack to functions as needed (and maintain
stack state).


Doesn't work on a mutithreaded environment...

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

..sig under repair

Nov 14 '05 #11

Le 15/06/2005 01:28, dans mn***********************@YOURBRAnoos.fr,
«*Emmanuel Delahaye*» <em***@YOURBRAnoos.fr> a écrit*:
Jean-Claude Arbaut wrote on 14/06/05 :
Oh, and in case you hadn't noticed: what I describe is a method used
in many F77 programs to pass arrays. F77 cannot allocate memory, so
the usual trick is: create a big data chunk (a global variable), wide enough
for all your needs, merely a heap. Then treat this "heap" as a stack,
and pass variables in that stack to functions as needed (and maintain
stack state).


Doesn't work on a mutithreaded environment...


Yes, but it was a trick to bypass F77 lack of dynamic allocation... No
threads there. But maybe you can hack F77 to make use of threads, I
really don't know, and that's another story. And if you try that in C with
malloc, it should be thread-friendly, after all you pass your variables to
functions, that's all !

Nov 14 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: ~Gee | last post by:
Hi Folks! Please see the program below: 1 #include<iostream> 2 #include<list> 3 #include <unistd.h> 4 using namespace std; 5 int main() 6 { 7 {
2
by: mosfets | last post by:
Hi, I'm having a little trouble figuring out the difference in terms of memory allocation between: class person_info; class A { private:
9
by: Mike P | last post by:
I know everything about reference counting and making sure you don't have large objects lying around. I have also profiled my app with multiple tools. I know about the fact GC collects memory but...
72
by: ravi | last post by:
I have a situation where i want to free the memory pointed by a pointer, only if it is not freed already. Is there a way to know whether the memory is freed or not?
62
by: ivan.leben | last post by:
How can I really delete a preloaded image from memory/disk cache? Let's say I preload an image by creating an Image object and setting its src attribute to desired URL: var img = new Image();...
9
by: Sundar | last post by:
Hi, i am trying to make an application that will require registering of quite a few dlls and execute. Now one of the first bottlenecks that my mentor refused is allocation of memory or the usage...
17
by: frederic.pica | last post by:
Greets, I've some troubles getting my memory freed by python, how can I force it to release the memory ? I've tried del and gc.collect() with no success. Here is a code sample, parsing an XML...
34
by: jacob navia | last post by:
Suppose that you have a module that always allocates memory without ever releasing it because the guy that wrote it was lazy, as lazy as me. Now, you want to reuse it in a loop. What do you do?...
66
by: karthikbalaguru | last post by:
Hi, Will 'free' return the memory Immediately to the OS ? Thx in advans, Karthik Balaguru
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.