473,666 Members | 2,047 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

GMPY: divm() memory leak revisited


Since the following discussion took place (unresolved),

<http://groups.google.c om/group/comp.lang.pytho n/browse_frm/thread/c3bd08ef3e4c478 a/2b54deb522c9b9d 9?lnk=st&q=divm ()+memory+leak+ group:comp.lang .python+author: mensanator&rnum =1&hl=en#2b54de b522c9b9d9>

I've kept it in the back of my mind as I've been
learning to use the base gmp library in c. Now I believe
I know what the problem is.

First, divm() is not a gmp function. It is a derived
function created in gmpy. It is derived from the
gmp invert() function (which I know from my testing
does not leak memory). So it's a gmpy specific bug.

Second, I learned from the gmp c library that temporary
mpz objects must be freed to prevent memory leak. Aha!
The gmpy source code is probably not freeing some temporary
mpz it created.

Third, we have the smoking gun:

divm(a,b,m): returns x such that b*x==a modulo m,
or else raises a ZeroDivisionErr or
exception if no such value x exists
(a, b and m must be mpz objects,
or else get coerced to mpz)

Of course, to "coerce" means to create temporary variables
to pass to the gmp library. It would appear that these
temporary variables are not being freed. Now if I'm right,
then I can prove this by eliminating the need to coerce
the operands by passing mpz's to the divm() function.

#
# if the parameters are already mpz's...
#
z = gmpy.mpz(812875 70543)
x = gmpy.mpz(858993 4592)
y = gmpy.mpz(348678 4401)
tot = 0
while True:
n = input('How many more divm: ')
if n<=0: break
print '%d more...' % n,
#
# ...then they won't need to be coerced
#
for i in xrange(n): gmpy.divm(z,x,y )
tot += n
print '...total %d' % tot
With coercing, I get

C:\Python23\use r\the_full_mont y>python gmpytest.py
How many more divm: 10000000
10000000 more...Fatal Python error: mp_allocate failure
abnormal program termination
peak Commit Charge (K): 792556

Without needing to coerce, the test ran to completion with
flat memory usage.

Unfortunately, c is still somewhat greek to me, but even so,
the problem appears obvious.

static PyObject *
Pygmpy_divm(PyO bject *self, PyObject *args)
{
PympzObject *num, *den, *mod, *res;
if(!PyArg_Parse Tuple(args, "O&O&O&",
Pympz_convert_a rg, &num,
Pympz_convert_a rg, &den,
Pympz_convert_a rg, &mod))
{
return last_try("divm" , 3, 3, args);
}
if(!(res = Pympz_new()))
return NULL;
if(mpz_invert(r es->z, den->z, mod->z)) { /* inverse exists */
mpz_mul(res->z, res->z, num->z);
mpz_mod(res->z, res->z, mod->z);
if(options.ZM_c b && mpz_sgn(res->z)==0) {
PyObject* result;
if(options.debu g)
fprintf(stderr, "calling %p from %s for %p %p %p %p\n",
options.ZM_cb, "divm", res, num, den, mod);
result = PyObject_CallFu nction(options. ZM_cb, "sOOOO",
"divm",
res, num, den, mod);
if(result != Py_None) {
Py_DECREF((PyOb ject*)res);
return result;
}
}
return (PyObject*)res;
} else {
PyObject* result = 0;
if(options.ZD_c b) {
result = PyObject_CallFu nction(options. ZD_cb,
"sOOO", "divm", num, den, mod);
} else {
PyErr_SetString (PyExc_ZeroDivi sionError, "not invertible");
}
Py_DECREF((PyOb ject*)res);
return result;
}
}

Note that 4 PympzObjects get created but only res gets passed to
Py_DECREF (which seems to be the method by which it's freed, not
100% sure about this). But I notice that other functions that
coerce variables call Py_DECREF on each of the coerced variables:

static PyObject *
Pygmpy_gcd(PyOb ject *self, PyObject *args)
{
PympzObject *a, *b, *c;
TWO_ARG_CONVERT ED("gcd", Pympz_convert_a rg,&a,&b);
assert(Pympz_Ch eck((PyObject*) a));
assert(Pympz_Ch eck((PyObject*) b));
if(!(c = Pympz_new())) {
Py_DECREF((PyOb ject*)a); Py_DECREF((PyOb ject*)b);
return NULL;
}
mpz_gcd(c->z, a->z, b->z);
Py_DECREF((PyOb ject*)a); Py_DECREF((PyOb ject*)b);
return (PyObject*)c;
}

Here the PympzObject c is not freed because it is returned
as the result of the function, but the coerced variables a and b
are.

So the fix may be to simply add

Py_DECREF((PyOb ject*)num);
Py_DECREF((PyOb ject*)den);
Py_DECREF((PyOb ject*)mod);

to divm(). (Assuming it's that simple, I could have overlooked
something.)

Unfortunately, I don't have any means of testing this theory.

I did see the reference to

<http://www.vrplumber.c om/programming/mstoolkit>

which I will be trying eventually, but in case I can't get that
to work I wanted to have this posted in case someone else wants
to take a crack at it.

Nov 5 '05 #1
3 2426
me********@aol. com wrote:
Since the following discussion took place (unresolved),

<http://groups.google.c om/group/comp.lang.pytho n/browse_frm/thread/c3bd08ef3e4c478 a/2b54deb522c9b9d 9?lnk=st&q=divm ()+memory+leak+ group:comp.lang .python+author: mensanator&rnum =1&hl=en#2b54de b522c9b9d9>

I've kept it in the back of my mind as I've been
learning to use the base gmp library in c. Now I believe
I know what the problem is.

First, divm() is not a gmp function. It is a derived
function created in gmpy. It is derived from the
gmp invert() function (which I know from my testing
does not leak memory). So it's a gmpy specific bug.

Second, I learned from the gmp c library that temporary
mpz objects must be freed to prevent memory leak. Aha!
The gmpy source code is probably not freeing some temporary
mpz it created.

Third, we have the smoking gun:

divm(a,b,m): returns x such that b*x==a modulo m,
or else raises a ZeroDivisionErr or
exception if no such value x exists
(a, b and m must be mpz objects,
or else get coerced to mpz)

Of course, to "coerce" means to create temporary variables
to pass to the gmp library. It would appear that these
temporary variables are not being freed. Now if I'm right,
then I can prove this by eliminating the need to coerce
the operands by passing mpz's to the divm() function.

#
# if the parameters are already mpz's...
#
z = gmpy.mpz(812875 70543)
x = gmpy.mpz(858993 4592)
y = gmpy.mpz(348678 4401)
tot = 0
while True:
n = input('How many more divm: ')
if n<=0: break
print '%d more...' % n,
#
# ...then they won't need to be coerced
#
for i in xrange(n): gmpy.divm(z,x,y )
tot += n
print '...total %d' % tot
With coercing, I get

C:\Python23\use r\the_full_mont y>python gmpytest.py
How many more divm: 10000000
10000000 more...Fatal Python error: mp_allocate failure
abnormal program termination
peak Commit Charge (K): 792556

Without needing to coerce, the test ran to completion with
flat memory usage.

Unfortunately, c is still somewhat greek to me, but even so,
the problem appears obvious.

static PyObject *
Pygmpy_divm(PyO bject *self, PyObject *args)
{
PympzObject *num, *den, *mod, *res;
if(!PyArg_Parse Tuple(args, "O&O&O&",
Pympz_convert_a rg, &num,
Pympz_convert_a rg, &den,
Pympz_convert_a rg, &mod))
{
return last_try("divm" , 3, 3, args);
}
if(!(res = Pympz_new()))
return NULL;
if(mpz_invert(r es->z, den->z, mod->z)) { /* inverse exists */
mpz_mul(res->z, res->z, num->z);
mpz_mod(res->z, res->z, mod->z);
if(options.ZM_c b && mpz_sgn(res->z)==0) {
PyObject* result;
if(options.debu g)
fprintf(stderr, "calling %p from %s for %p %p %p %p\n",
options.ZM_cb, "divm", res, num, den, mod);
result = PyObject_CallFu nction(options. ZM_cb, "sOOOO",
"divm",
res, num, den, mod);
if(result != Py_None) {
Py_DECREF((PyOb ject*)res);
return result;
}
}
return (PyObject*)res;
} else {
PyObject* result = 0;
if(options.ZD_c b) {
result = PyObject_CallFu nction(options. ZD_cb,
"sOOO", "divm", num, den, mod);
} else {
PyErr_SetString (PyExc_ZeroDivi sionError, "not invertible");
}
Py_DECREF((PyOb ject*)res);
return result;
}
}

Note that 4 PympzObjects get created but only res gets passed to
Py_DECREF (which seems to be the method by which it's freed, not
100% sure about this). But I notice that other functions that
coerce variables call Py_DECREF on each of the coerced variables:

static PyObject *
Pygmpy_gcd(PyOb ject *self, PyObject *args)
{
PympzObject *a, *b, *c;
TWO_ARG_CONVERT ED("gcd", Pympz_convert_a rg,&a,&b);
assert(Pympz_Ch eck((PyObject*) a));
assert(Pympz_Ch eck((PyObject*) b));
if(!(c = Pympz_new())) {
Py_DECREF((PyOb ject*)a); Py_DECREF((PyOb ject*)b);
return NULL;
}
mpz_gcd(c->z, a->z, b->z);
Py_DECREF((PyOb ject*)a); Py_DECREF((PyOb ject*)b);
return (PyObject*)c;
}

Here the PympzObject c is not freed because it is returned
as the result of the function, but the coerced variables a and b
are.

So the fix may be to simply add

Py_DECREF((PyOb ject*)num);
Py_DECREF((PyOb ject*)den);
Py_DECREF((PyOb ject*)mod);

to divm(). (Assuming it's that simple, I could have overlooked
something.)

Unfortunately, I don't have any means of testing this theory.

I did see the reference to

<http://www.vrplumber.c om/programming/mstoolkit>

which I will be trying eventually, but in case I can't get that
to work I wanted to have this posted in case someone else wants
to take a crack at it.

I completely forgot to mention the fourth thing I discovered.

The linear congruence algorithm used in divm() is wrong. To wit:
divm(6,12,14)
Traceback (most recent call last):
File "<pyshell#4 >", line 1, in -toplevel-
divm(6,12,14)
ZeroDivisionErr or: not invertible

Sure, (12,14) is not invertible, but that is not a requirement for
solving a linear congruence. All that's required is that gcd(12,14)
divides 6, which it obviously does. The divm() function cannot
handle the case when b and m are not coprime. A properly
written linear congruence algorithm will work around the fact
that (12,14) is not invertible. To wit:
linear_congruen ce(12,14,6)

mpz(4)

The correct algorithm can't solve a problem that's not solvable,
but it shouldn't let non-invertability cause an exception. Here's
the correct algorithm which divm() ought to incorprorate.

from gmpy import *
def linear_congruen ce(x,y,z):
#
# xa == z (mod y)
#
g = gcd(x,y)
d = divmod(z,g)
if d[1]==0:
#
# gcd(x,y) divides z, solution exists
#
if g==1:
#
# x,y coprime, modular inverse exists
#
a = invert(x,y)*z % y
else:
#
# x,y not coprime, no modular inverse
# ...but wait, if we get here g divides z and also
# by definition, x & y, so divide x,y,z by g to create
# a new congruence with x,y now coprime and invert() valid
#
x = x/g
y = y/g
z = z/g
a = invert(x,y)*z % y
else:
#
# g doesn't divide z, no solution
#
a = -1
return a

Nov 5 '05 #2
me********@aol. com <me********@aol .com> wrote:
...
Unfortunately, I don't have any means of testing this theory.


Yep -- I reproduced the memory leak you mentioned, and easily fixed it
(exactly as you suggest) in the current CVS version of gmpy (meant to be
"1.01 release candidate"). I need to fix some other pending bugs, then
remind myself of how the (expl.del) one makes a release on Sourceforge,
then it shd be fine (except for Windows -- I have no Windows development
system around to do anything... Mac and Linux only).

One of the bugs I must still get around to examining is the algorithmic
one you mention in your next post, btw.

Thanks for your diagnostic and debugging help. BTW, should you wish to
mail me privately, I'm "aleaxit" (my favourite userid, with or w/o the
trailing "it" depending on service -- see www.aleax.com to understand
why that is the case), and the best way to reach me these days is
through "gmail.com" .
Alex
Nov 6 '05 #3

Alex Martelli wrote:
me********@aol. com <me********@aol .com> wrote:
...
Unfortunately, I don't have any means of testing this theory.
Yep -- I reproduced the memory leak you mentioned, and easily fixed it
(exactly as you suggest) in the current CVS version of gmpy (meant to be
"1.01 release candidate"). I need to fix some other pending bugs, then
remind myself of how the (expl.del) one makes a release on Sourceforge,
then it shd be fine


That's great!
(except for Windows -- I have no Windows development
system around to do anything... Mac and Linux only).
Well, I hope someone makes a Windows binary once you publish ver 1.01.
I downloaded all that MSVC command line stuff (over 800 MB!) but am not
looking forward to trying to get it to work.

One of the bugs I must still get around to examining is the algorithmic
one you mention in your next post, btw.

Thanks for your diagnostic and debugging help. BTW, should you wish to
mail me privately, I'm "aleaxit" (my favourite userid, with or w/o the
trailing "it" depending on service -- see www.aleax.com to understand
why that is the case), and the best way to reach me these days is
through "gmail.com" .
Alex


Nov 6 '05 #4

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

Similar topics

22
1946
by: Alex Martelli | last post by:
I have fixed almost all of the outstanding bugreports and feature request for gmpy: divm doesn't leak memory any more, truediv and floordiv are implemented for all types, etc -- in the current CVS version (one thing I must still look at is divm's behavior when its args are not mutually prime). It currently compiles w/o warnings, and passes all of its 1040+ tests, w/the current release of GMP (4.1.4), Python (2.4.2), MacOSX (10.4.3), XCode...
8
3408
by: ranjeet.gupta | last post by:
Dear All Is the Root Cause of the Memory corruption is the Memory leak, ?? suppose If in the code there is Memory leak, Do this may lead to the Memory Corruption while executing the program ? In nut shell, what is/are the realtion/s between the Memory Leak and Memory Corruption. Juts Theoritical Assumtion below:
17
4798
by: José Joye | last post by:
Hi, I have implemented a Service that is responsible for getting messages from a MS MQ located on a remote machine. I'm getting memory leak from time to time (???). In some situation, it is easier to reproduce (e.g.: remote machine not available). After about 1 day, I get a usage of 300MB of memory. I have used .NET Memory Profiler tool to try to see where the leak is located. For all the leaky instances, I can see the following (I...
20
8092
by: jeevankodali | last post by:
Hi I have an .Net application which processes thousands of Xml nodes each day and for each node I am using around 30-40 Regex matches to see if they satisfy some conditions are not. These Regex matches are called within a loop (like if or for). E.g. for(int i = 0; i < 10; i++) { Regex r = new Regex();
23
4545
by: James | last post by:
The following code will create memory leaks!!! using System; using System.Diagnostics; using System.Data; using System.Data.SqlClient; namespace MemoryLeak
18
2927
by: diffuser78 | last post by:
I have a python code which is running on a huge data set. After starting the program the computer becomes unstable and gets very diffucult to even open konsole to kill that process. What I am assuming is that I am running out of memory. What should I do to make sure that my code runs fine without becoming unstable. How should I address the memory leak problem if any ? I have a gig of RAM. Every help is appreciated.
3
2222
by: mensanator | last post by:
## Holy Mother of Pearl! ## ## >>> for i in range(10): ## for j in range(10): ## print '%4d' % (gmpy.mpz(i)*gmpy.mpz(j)), ## print ## ## ## 0 0 0 0 0 0 0 0 0 0 ## 0 1 2 3 1 5 6 7 2 9
3
5311
by: Jim Land | last post by:
Jack Slocum claims here http://www.jackslocum.com/yui/2006/10/02/3-easy-steps-to-avoid-javascript- memory-leaks/ that "almost every site you visit that uses JavaScript is leaking memory". Anybody know anything about this? Does *Javascript* leak memeory, or does the *browser* leak memory?
22
9332
by: Peter | last post by:
I am using VS2008. I have a Windows Service application which creates Crystal Reports. This is a multi theaded application which can run several reports at one time. My problem - there is a memory leak someplace. I can not detect the memory leak by running several reports by hand, but when I run tha app as a servrice and process few hundred reports there is significant memory leak. The application can consume over 1GB of memory where it...
0
8448
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
8783
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8640
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
6198
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
5666
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
4198
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
4369
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1776
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.