473,699 Members | 2,254 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

calloc/free: a preplexing observation

Hi!

I'm seeking some answers about what seems to be a memory leak.

I have a loop that looks much like this:
double *largeArray = (double*) calloc();
for (...) {
printf("iterati on #...\n");
for (...) {
double *foo = (double*) calloc();
.....
.....
largeArray[someIndex] = something;
free(foo);
}
}

Though the actual code is larger, it only differs in 20+ lines of
trivial math performed on stack variables.

Clearly, foo cannot be leaking since it's being freed (and no, it
cannot be allocated outside of the loop, since its size varies each
time.

Now, when I monitor memory usage with top it grows relatively quickly
(300K per pass over the outer loop), thus there ought to be a memory
leak. At first I thought that the "largeArray " was being optimized not
to calloc all at once, but rather on demand, page by page (which would
be bizzarre) but now I believe that might not be the case since the
"largeArray " is about 4000*4000 of double which should be about 16MB -
and I see usage of > 100MB after a few hundred iterations.

I'm using gcc 3.2.2 on i*86 Linux.
Any guesses would be appreciated.

Thanks!

Boris

Nov 14 '05 #1
40 2518
j

<bo***@borislan d.com> wrote in message
news:11******** **************@ c13g2000cwb.goo glegroups.com.. .
Hi!

I'm seeking some answers about what seems to be a memory leak.

I have a loop that looks much like this:
double *largeArray = (double*) calloc();
for (...) {
printf("iterati on #...\n");
for (...) {
double *foo = (double*) calloc();
....
....
largeArray[someIndex] = something;
free(foo);
}
}

Though the actual code is larger, it only differs in 20+ lines of
trivial math performed on stack variables.

Clearly, foo cannot be leaking since it's being freed (and no, it
cannot be allocated outside of the loop, since its size varies each
time.

Now, when I monitor memory usage with top it grows relatively quickly
(300K per pass over the outer loop), thus there ought to be a memory
leak. At first I thought that the "largeArray " was being optimized not
to calloc all at once, but rather on demand, page by page (which would
be bizzarre) but now I believe that might not be the case since the
"largeArray " is about 4000*4000 of double which should be about 16MB -
and I see usage of > 100MB after a few hundred iterations.

I'm using gcc 3.2.2 on i*86 Linux.
Any guesses would be appreciated.


I really do not see an issue with the code you have provided.
(Other than casting where unnecessary). It is too incomplete.
Can you not provide all of it? If not, I would recommend the
use of valgrind here. But that is off-topic for this newsgroup.

--
j
Nov 14 '05 #2
In article <11************ **********@c13g 2000cwb.googleg roups.com>,
<bo***@borislan d.com> wrote:
"largeArray " is about 4000*4000 of double which should be about 16MB -


4000*4000 doubles is 16M * sizeof(double), which is 128MB if you have
8-byte doubles.

-- Richard
Nov 14 '05 #3
On 2005-01-31 12:18:44 -0500, bo***@borisland .com said:
Hi!

I'm seeking some answers about what seems to be a memory leak.
[snip]
... since the
"largeArray " is about 4000*4000 of double which should be about 16MB -
and I see usage of > 100MB after a few hundred iterations.


Do the math again:

4,000 * 4,000
= 16,000,000

If sizeof(double) is 8 then:

8B * 16,000,000
= 128,000,000B
≈ 122 MB

So your usage of > 100MB seems to be right in line with what should be
expected.

--
Clark S. Cox, III
cl*******@gmail .com

Nov 14 '05 #4
Right-O. I'm an idiot: >100MB is exactly the right space usage.
However, why is it not all allocated with the first calloc of
largeArray - why do I see 'top' report ever-growing usage? This is
where I would probably want to use -fprefetch-loop-arrays, which is not
supported on my architecture according to gcc :)

As for providing more code, I could - but the rest of it is just junk -
this is all of the relevant code.

Boris

bo***@borisland .com wrote:
Hi!

I'm seeking some answers about what seems to be a memory leak.

I have a loop that looks much like this:
double *largeArray = (double*) calloc();
for (...) {
printf("iterati on #...\n");
for (...) {
double *foo = (double*) calloc();
....
....
largeArray[someIndex] = something;
free(foo);
}
}

Though the actual code is larger, it only differs in 20+ lines of
trivial math performed on stack variables.

Clearly, foo cannot be leaking since it's being freed (and no, it
cannot be allocated outside of the loop, since its size varies each
time.

Now, when I monitor memory usage with top it grows relatively quickly
(300K per pass over the outer loop), thus there ought to be a memory
leak. At first I thought that the "largeArray " was being optimized not to calloc all at once, but rather on demand, page by page (which would be bizzarre) but now I believe that might not be the case since the
"largeArray " is about 4000*4000 of double which should be about 16MB - and I see usage of > 100MB after a few hundred iterations.

I'm using gcc 3.2.2 on i*86 Linux.
Any guesses would be appreciated.

Thanks!

Boris


Nov 14 '05 #5
bo***@borisland .com wrote:
Right-O. I'm an idiot: >100MB is exactly the right space usage.
However, why is it not all allocated with the first calloc of
largeArray - why do I see 'top' report ever-growing usage? This is
where I would probably want to use -fprefetch-loop-arrays, which is not
supported on my architecture according to gcc :)

As for providing more code, I could - but the rest of it is just junk -
this is all of the relevant code.
But it will not work when pasted into some sort of main() function.
Boris

bo***@borisland .com wrote:
Hi!

I'm seeking some answers about what seems to be a memory leak.

I have a loop that looks much like this: #include <stdlib.h>
#include <stdio.h>

int main (void)
{double *largeArray = (double*) calloc(); how much are you calloc()ing.for (...) { where are you looping
printf("itera tion #...\n");
for (...) { dito
double *foo = (double*) calloc(); how much are you calloc()ing....
....
largeArray[someIndex] = something; where are someindex and something declared/initialized
free(foo);
}
} where is largeArray free()d

return 0;
}

Now, give us that stuff requested or create a minimal example --
then we can help you.

Note that calloc() does not necessarily make sense for doubles

Please do not top-post.
Cheers
Michael
Though the actual code is larger, it only differs in 20+ lines of
trivial math performed on stack variables.

Clearly, foo cannot be leaking since it's being freed (and no, it
cannot be allocated outside of the loop, since its size varies each
time.

Now, when I monitor memory usage with top it grows relatively quickly
(300K per pass over the outer loop), thus there ought to be a memory
leak. At first I thought that the "largeArray " was being optimized


not
to calloc all at once, but rather on demand, page by page (which


would
be bizzarre) but now I believe that might not be the case since the
"largeArray " is about 4000*4000 of double which should be about 16MB


-
and I see usage of > 100MB after a few hundred iterations.

I'm using gcc 3.2.2 on i*86 Linux.
Any guesses would be appreciated.

Thanks!

Boris


--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #6
bo***@borisland .com writes:
I'm seeking some answers about what seems to be a memory leak.

I have a loop that looks much like this:
double *largeArray = (double*) calloc();
for (...) {
printf("iterati on #...\n");
for (...) {
double *foo = (double*) calloc();
....
....
largeArray[someIndex] = something;
free(foo);
}
}

Though the actual code is larger, it only differs in 20+ lines of
trivial math performed on stack variables.

Clearly, foo cannot be leaking since it's being freed (and no, it
cannot be allocated outside of the loop, since its size varies each
time.

Now, when I monitor memory usage with top it grows relatively quickly
(300K per pass over the outer loop), thus there ought to be a memory
leak. At first I thought that the "largeArray " was being optimized not
to calloc all at once, but rather on demand, page by page (which would
be bizzarre) but now I believe that might not be the case since the
"largeArray " is about 4000*4000 of double which should be about 16MB -
and I see usage of > 100MB after a few hundred iterations.


Apart from your miscalculation of the size allocated for largeArray,
there's no guarantee that free() gives memory back to the operating
system. Very likely it stays within your program and becomes
available for further allocation. You don't give us a clue about what
arguments you're giving to calloc(), but it's possible that you're
fragmenting the heap and making it difficult for the system to
re-allocate the memory you've freed.

I would probably add some printf() statements to log all the calls to
calloc() and free(). For example:

double *foo = calloc(somethin g, something_else) ;
/*
* don't cast the result of malloc() or calloc().
*/
printf("foo = calloc("%lu, %lu) --> [%p]\n",
(unsigned long)something,
(unsigned long)something_ else,
(void*)foo);
...
printf("free(fo o), foo=[%p]\n", (void*)foo);
free(foo);

Analyze the results and make sure you're freeing everything you
allocate. If not, there's your problem; if so, the displayed
addresses may tell you something, or there may be some system-specific
way to trace the internal behavior of calloc() and free().

Incidentally, it's not safe to assume that calloc() will set all the
doubles in your allocated array to 0.0. It sets the allocated memory
to all-bits-zero. This is often the representation of 0.0, but the
language doesn't guarantee it.

--
Keith Thompson (The_Other_Keit h) 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 #7
bo***@borisland .com wrote:
Right-O. I'm an idiot: >100MB is exactly the right space usage.
However, why is it not all allocated with the first calloc of
largeArray - why do I see 'top' report ever-growing usage? This is
where I would probably want to use -fprefetch-loop-arrays, which is not supported on my architecture according to gcc :)


Probably your operating system is doing 'lazy allocation'. It will
allocate you an address space but not actually claim that memory yet.

Then when you try and access memory in the space you have been
given, it will go and actually allocate that memory.

If there is not actually any memory available then it will die
in a screaming heap, or start swapping endlessly.

I think the point of lazy allocation is so that if a programmer
is lazy and just mallocs a huge chunk at the start, then other
applications do not need to suffer the effects of having not
much memory available.

Nov 14 '05 #8
"Old Wolf" <ol*****@inspir e.net.nz> writes:
bo***@borisland .com wrote:
Right-O. I'm an idiot: >100MB is exactly the right space usage.
However, why is it not all allocated with the first calloc of
largeArray - why do I see 'top' report ever-growing usage? This is
where I would probably want to use -fprefetch-loop-arrays, which is
not supported on my architecture according to gcc :)


Probably your operating system is doing 'lazy allocation'. It will
allocate you an address space but not actually claim that memory yet.

Then when you try and access memory in the space you have been
given, it will go and actually allocate that memory.

If there is not actually any memory available then it will die
in a screaming heap, or start swapping endlessly.

I think the point of lazy allocation is so that if a programmer
is lazy and just mallocs a huge chunk at the start, then other
applications do not need to suffer the effects of having not
much memory available.


It's pretty clear that lazy allocation is non-conforming. A program
should be able to determine whether enough memory is available when it
attempts to allocate it; that's why malloc() provides a simple and
clear mechanism for reporting failure. There's no way a program can
fail gracefully if the OS randomly kills it when it tries to access
memory it thinks it's already allocated.

The OP was using calloc(), which zeros the allocated memory, but
perhaps the system simulates that (so that the memory which springs
into existence when it's accessed looks like it's already filled with
zeros).

If your system does lazy allocation, one way to make it act as if it
were more nearly conforming would be to fill the allocated memory
with, say, 0xff bytes immediately after allocating it. That still
won't let it fail gracefully, but at least the failure will occur
sooner rather than later.

An experiment the OP might try is to fill the allocated memory with
some non-zero value immediately after calloc(), then fill it with
zeros again. Obviously this is going to slow things down (so you
won't want to do this in your production version), but it could be
useful to see whether this affects the memory behavior.

--
Keith Thompson (The_Other_Keit h) 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 #9
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.or g> wrote:
An experiment the OP might try is to fill the allocated memory with
some non-zero value immediately after calloc(), then fill it with
zeros again. Obviously this is going to slow things down (so you
won't want to do this in your production version), but it could be
useful to see whether this affects the memory behavior.


I have seen exactly this method being used in serious production code -
a function "my_malloc ()" with the same arguments as malloc, that would
call malloc (), install a signal handler, fill the malloc ()'d pointer
with some data, and finally return the pointer. If anything went wrong
while filling the allocated memory, the signal handler would stop the
signal from propagating; in that case the pointer was free()d and the
function returned NULL. Truly horrible code to attempt to get a
conforming implementation.
Nov 14 '05 #10

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

Similar topics

43
3403
by: M-One | last post by:
See subject: how do I calloc (and free the memory, if that's not free(my_bytes);) this? TIA!
5
3637
by: Koster | last post by:
Sorry for the re-post, but my previous question was left unanswered. I have a question about the appropriateness of calloc. Consider an array of pointers to structs which need to be allocated space on the heap, for example: typedef struct myStruct *PMYSTRUCT; struct myStruct { int i; int j;
29
40392
by: David Hill | last post by:
Is there a difference between: /* code 1 */ struct sample test; test = malloc(sizeof(struct sample)); memset(&test, 0, sizeof(test)); /* code 2 */ struct sample test; test = calloc(1, sizeof(struct sample));
37
2569
by: Harsimran | last post by:
Can any one explain what are far pointers and what is the difference between malloc and calloc .Which is better ?
2
1744
by: chingfulan | last post by:
I have the following code and I can not figure out why Stg2In returns a null pointer? "Stg2In = (float *)calloc(9*DataLen, sizeof(float)); " while "Stg2Out = (float *)calloc(9*DataLen, sizeof(float));" is sucessful? Can anyone Help? Thx
14
7489
by: Roka100 | last post by:
Hi all, I tried 2 programs : #include <stdio.h> #include <string.h> 1, int main(void){ char *str = NULL;
13
2529
by: ababeel | last post by:
Hi I am using a calloc in a hash table program on an openvms system. The calloc is used to declare the hash table char **pHashes; pHashes = calloc(hash_size,sizeof(char *)); //hash_size = 101 and then later on when it is half full i do the following char **newHashes; if(newHashes)
6
4926
by: mthread | last post by:
Hi, I am learning C++ and I have been told that an object can be created either by using calloc or new. If it is true, can some one tell me what is the difference b/w using these two function calls.
3
2166
by: anjanaanupindi | last post by:
#include<stdio.h> #include<ccblkfn.h> #include<cdefbf533.h> //BF533 Register Pointer Definition #include<defbf533.h> section("sdram0_data") float *p;
0
8685
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
8613
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
9172
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...
1
8908
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8880
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...
0
7745
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6532
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
4374
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...
0
4626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.