473,837 Members | 1,524 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to release memory?


I use free() function to release memory,
But the memory usage is still increasing.

cygwin

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct queue{
char data[1024];
struct queue *next;
};
struct queue *myqueue[1024];
struct queue *pre_item[1024];
struct queue *first_item[1024];

void enqueue(int sockfd,char *var){
myqueue[sockfd]=(struct queue *) malloc(sizeof (struct queue));
strcpy((char *)&myqueue[sockfd]->data,var);
myqueue[sockfd]->next=NULL;
if (pre_item[sockfd]!=NULL){
pre_item[sockfd]->next=myqueue[sockfd];
}else{
first_item[sockfd]=myqueue[sockfd];
}
pre_item[sockfd]=myqueue[sockfd];
}

char *dequeue(int sockfd){
char r[1024];
struct queue *temp;
temp=first_item[sockfd];
strcpy(r,temp->data);
first_item[sockfd]=first_item[sockfd]->next;
temp=NULL;
free(temp);
return r;
}
Jun 27 '08 #1
36 3242

"mynews" <no******@gmail .comwrote in message
news:g3******** *@netnews.hinet .net...
>
I use free() function to release memory,
But the memory usage is still increasing.
What did you do to determine that?

Note that many operating systems will keep
free'd memory in reserve for an application
until it exits.

How exactly this is done depends upon your
operating system, implementation, and possibly
other factors.

I didn't look closely at your code, so I can't
say if it actually leaks or not.

If you want to test for 'real' memory leaks,
I suggest a tool made for it, e.g. valgrind.

-Mike

Jun 27 '08 #2
On Jun 26, 8:20 am, "mynews" <norep...@gmail .comwrote:
I use free() function to release memory,
But the memory usage is still increasing.
temp=NULL;
free(temp);
Since when are you allowed to call free(NULL)?
May be what you want is :
free(temp);
temp = NULL;

I have not seen your code carefully but the approach seems to be
flawed. You are maintaining 3 array of pointers, each 1024 elements,
to implement a simple queue. Further, you are freeing only elements in
first_item (well, as of now, not even that). What about the elements
of per_item? Your logic is not clear to me. Perhaps you should re-
consider your data structures and algorithms.
Jun 27 '08 #3
rahul said:
On Jun 26, 8:20 am, "mynews" <norep...@gmail .comwrote:
>I use free() function to release memory,
But the memory usage is still increasing.
> temp=NULL;
free(temp);

Since when are you allowed to call free(NULL)?
Since at least 1989.

It's a bit pointless, since it does nothing whatsoever, but it's legal.
May be what you want is :
free(temp);
temp = NULL;
Probably, yes.

<snip>

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #4
rahul <ra*********@gm ail.comwrites:
On Jun 26, 8:20 am, "mynews" <norep...@gmail .comwrote:
I use free() function to release memory,
But the memory usage is still increasing.
temp=NULL;
free(temp);

Since when are you allowed to call free(NULL)?
May be what you want is :
free(temp);
temp = NULL;
[...]

You're certainly allowed to call free(NULL). It does nothing.

And that's (at least part of) the problem. The memory leak occurs
when he assigns ``temp=NULL;'', thereby losing the value of the
pointer that he wants to free.

There are numerous other problems, which I'll go over in a separate
followup.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #5
rahul wrote:
Since when are you allowed to call free(NULL)?
K&R2 is copyrighted 1988.

Appendix B, B5, says
"void free(void *p)
free deallocates the space pointed to by p,
it does nothing if p is NULL."

--
pete
Jun 27 '08 #6
"mynews" <no******@gmail .comwrites:
I use free() function to release memory,
But the memory usage is still increasing.

cygwin

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct queue{
char data[1024];
struct queue *next;
};
struct queue *myqueue[1024];
struct queue *pre_item[1024];
struct queue *first_item[1024];
Three arrays of pointers seems excessive. I'm sure there's a simpler
way to do this, but I'll just deal with C issues here.
void enqueue(int sockfd,char *var){
myqueue[sockfd]=(struct queue *) malloc(sizeof (struct queue));
Don't cast the result of malloc(). The recommended idiom for this is:
myqueue[sockfd] = malloc(sizeof *myqueue[sockfd]);
More generally:
ptr = malloc(sizeof *ptr);
or
ptr = malloc(N * sizeof *ptr);
You can add parentheses if you like:
ptr = malloc(sizeof(* ptr));
strcpy((char *)&myqueue[sockfd]->data,var);
Most casts are unnecessary. This one, I suspect, was added to
suppress a warning. Adding a cast to supress a warning is like
disconnecting a warning light on your car's dashboard; the problem is
still there.

strcpy() expects a char* as its first argument.
``myqueue[sockfd]->data'' is of type char[1024], which decays to
char* in most contexts, so that's exactly what you want:

strcpy(myqueue[sockfd]->data, var);

What you've done is take the address of the array, which is of type
char(*)[1024], and then forcibly converted that to the expected type.

myqueue[sockfd]->next=NULL;
if (pre_item[sockfd]!=NULL){
pre_item[sockfd]->next=myqueue[sockfd];
}else{
first_item[sockfd]=myqueue[sockfd];
}
pre_item[sockfd]=myqueue[sockfd];
}

char *dequeue(int sockfd){
char r[1024];
struct queue *temp;
temp=first_item[sockfd];
strcpy(r,temp->data);
first_item[sockfd]=first_item[sockfd]->next;
temp=NULL;
free(temp);
You need to set temp to NULL *after* calling free().

For that matter, since temp is just about to go out of scope, there's
no need to set it to NULL.
return r;
r is a local variable of type char[1024]. It decays to a pointer to
its first element. Returning a pointer to a local variable is A Bad
Thing. You're giving the caller a pointer to something that will
no longer exist.
}
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #7
Keith Thompson wrote:
"mynews" <no******@gmail .comwrites:
> temp=NULL;
free(temp);

You need to set temp to NULL *after* calling free().

For that matter, since temp is just about to go out of scope, there's
no need to set it to NULL.
It might be good practice to set temp to NULL. The code may grow in future
or it may be copied elsewhere.

Probably the compiler will eliminate it in this case.

--
Bartc
Jun 27 '08 #8
Bartc wrote:
Keith Thompson wrote:
>"mynews" <no******@gmail .comwrites:
>> temp=NULL;
free(temp);

You need to set temp to NULL *after* calling free().

For that matter, since temp is just about to go out of scope, there's
no need to set it to NULL.

It might be good practice to set temp to NULL. The code may grow in future
or it may be copied elsewhere.
Or it might not. Or reading the superfluous line of code might be
the last straw and send some poor programmer round the twist. Or
the extra bytes might overflow the disc. Or Cthulhu might turn up.

If the code /does/ grow or get copied, then appropriate action may
be taken.

--
"The letter was not unproductive." /Mansfield Park/

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England

Jun 27 '08 #9
pereges wrote:
I also have a few doubts with regard to releasing memory and other
resources. When an error occurs at some point in the program then
usually we proceed by printing an error message and propogating a flag
backwards ( return (1) ) indicating error. Is it a good policy to
release all the resources which were held up till then (when the error
occured) in the program. For eg. a file may be open which must be
closed, a data structure that must be freed etc. It can vary at
different points in the program, different resources may have to be
freed depending on what was allocated till that point. At the very end
(just before main process ends) all the resources can be freed.
You have the right idea. It's always good practise to release resources
held after a critical failure. Modern OSes may be able to recover
memory even if you do not free it before the program terminates, but
other resources like file streams may still need flushing, and this may
not happen automatically during abnormal termination.

In C this is generally done by propagating the critical failure up the
call stack, with each function cleaning up it's resources, all the way
up to main. Of course, this is tedious and may not be practical for
large programs. You might find that it often easier to just exit from
many important functions rather than go all the way back to main for
every error. If you need to invariably perform certain actions at exit,
then you can register the concerned functions with atexit. You should
generally reserve abort and _Exit for serious conditions like internal
inconsistency.

Jun 27 '08 #10

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

Similar topics

6
3856
by: ss | last post by:
Hi I built an exe in console debug mode & Release mode . The console debug mode -exe works fine ...but the release mode EXE starts well but fails mid way . The exe is being started as a service. So I need the Release mode EXE. I've checked the dlls being used . they are working fine for other services.
0
1363
by: gchandran | last post by:
Hi All, Problem: Call to DOMDocument::getElementsByTagName() in a loop causes growth in memory consumption? Consider the following lines of code which simulates the problem that I am facing. ///////////////////////////////////////////////////////////////// m_doc = m_parser->getDocument() ;
7
2590
by: Techno Learner | last post by:
Sorry for the lame question but, what's the difference between Debug and Release versions?
3
3335
by: Marc | last post by:
I am using Visual Studio 2003 with .NET Framework 1.x on XP SP2. I am executing the following code (see also http://dturini.blogspot.com/2004/06/on-past-few-days-im-dealing-with-som e.html) HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com/"); using (HttpWebResponse wrp = (HttpWebResponse)wr.GetResponse()) { using (Stream s = wrp.GetResponseStream())
1
2084
by: spiff | last post by:
We are migrating from VC++ 6 to VC++ 2003. It is a plain, unmanaged application with both C and C++ source. When running the debug build, even outside the debugger, the memory allocation/deallocation performance appears to be orders of magnitude slower than in VC++ 6. The release build runs fine - no performance problems. We've rewritten some of the code to do fewer memory allocations/deallocations and that has helped those pieces. However,...
10
1594
by: babak | last post by:
Hi everybody I'm working with a project in embedded Visual Studio 4 and I have a general problem which I hope that somebody can help me with. My problem is the following: My project works fine in debug version but behaves strangely and sometimes crashes when I run it in release version. I suspect that it is some sort of memory problem but it is not that easy to find out what the problem exactly is (the project is rather big with maybe...
5
1939
by: Rodrigue | last post by:
I have code where I populate a data table using visual basic.net code. I call the clear method on the table but it does not seem to release the memory. When I populate the table again, the memory used by the application seems to keep increasing . the code I use seems to be pretty straightforward QueueRowTable.Clear() The memory is never reclaimed. What do I need to do to release the memory to the system? Thanks for any help.
2
1683
by: ABC | last post by:
How should I to release the pop-up page object on memory when I close the page? I have main page, which will open a popup webpage when a button clicked. In the first opened pop-up page, it is no problem. After closed pop-up page, then second click button, it don't run over the Page_Load event of the pop-up page. I think it have page object storage on memory. How should I to release the page object when I closed pop-up page.
2
2383
by: Epetruk | last post by:
Hello, I have a problem where an application I am working on throws an OutOfMemoryException when I run it in Release mode, whereas it doesn't do this when I am running in Debug. The application is developed using C++/Managed C++ and built using VS 2003 under .NET framework 1.1. In Debug, it uses of up to 600Mb of memory, whereas in Release it only gets
7
2830
by: Dmitriy V'jukov | last post by:
On Jun 16, 3:09 pm, Anthony Williams <anthony....@gmail.comwrote: Yes, I've already read this. It's just GREAT! It's far more useful and intuitive. And it contains clear and simple binding to memory model, i.e. relations between acquire/release fences; and between acquire/release fences and acquire/release operations.
0
9843
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9682
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10881
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10275
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7807
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7004
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5670
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4475
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3126
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.