473,563 Members | 2,653 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory leaks with realloc()

The bigint struct defines a big integer and represents it as a string of
characters:

typedef struct bigint {
int sign;
int size;
int initflag;
char *number;
} bigint;

In the code below I am initializing a bigint to zero with malloc() then
realloc()-ing in bigAlloc() and the two assignment functions. Do I have
a memory leak anywhere in this code? In particular, once the bigint has
been initialized do I need to free the currently allocated memory before
reallocating in bigAlloc() and the bigAssign()s?

/* initialize a bigint to zero */
void bigInit(bigint *a)
{
if((a->number = malloc(2))==NUL L)
{
fprintf(stderr, "malloc failed in bigInit()\n");
exit(EXIT_FAILU RE);
}
a->sign = POS;
a->size = 1;
a->initflag = 1;
a->number[0] = '0';
a->number[1] = '\0';
return;
}

/* allocate memory for a bigint */
void bigAlloc(bigint *a, int bytes)
{
if(a->initflag != 1)
{
bigInit(a);
}

if((a->number = realloc(a->number, bytes * sizeof(*a->number)))==NUL L)
{
fprintf(stderr, "bigAlloc failed\n");
exit(EXIT_FAILU RE);
}
return;
}

/* bigint assignment: a = b */
void bigAssign(bigin t *a, bigint b)
{
bigAlloc(a, b.size+1);
if(b.sign == POS) a->sign = POS;
if(b.sign == NEG) a->sign = NEG;
a->size = b.size;
strcpy(a->number, b.number);
return;
}

/* assignment */
void bigAssignByRef( bigint *a, bigint *b)
{
bigAlloc(a, b->size+1);
if(b->sign == POS) a->sign = POS;
if(b->sign == NEG) a->sign = NEG;
a->size = b->size;
strcpy(a->number, b->number);
return;
}
Nov 14 '05 #1
7 2914


Marlene Stebbins wrote:
[...] Do I have
a memory leak anywhere in this code?
You have a potential leak in bigAlloc() at
if((a->number = realloc(a->number, ...))==NULL)
.... because if realloc() fails you will overwrite the still-
valid pointer `a->number' with NULL. Unless you have another
pointer somewhere that retains the former value of `a->number',
you have lost all ability to do anything with the memory that
`a->number' used to point to; you have "leaked" that memory.

However, in your case the leak is not serious, because if
realloc() fails you call `exit(EXIT_FAIL URE)'. The duration
of the leak will be short, and its effect on the subsequent
operation of the program practically nil ;-)
In particular, once the bigint has
been initialized do I need to free the currently allocated memory before
reallocating in bigAlloc() and the bigAssign()s?
You should *not* free() a memory area and then try to
realloc() it. The first argument to realloc() must be NULL
or must be a pointer to a currently-valid memory area as
allocated by malloc(), calloc(), or a previous realloc() --
if you hand realloc() a pointer to anything else, you get
undefined behavior.

In your case, though, it might make more sense to free()
and malloc() than to realloc() -- you do not need to preserve
the former contents of the memory `a->number' points to; you
are about to insert brand-new content. Thus, whatever extra
work realloc() undertakes to preserve the original bytes is
simply a waste. Indeed, free()/malloc() may succeed where a
realloc() would have failed; for your purposes realloc() is
not only less efficient, but less effective.

One additional remark: Why write
if(b.sign == POS) a->sign = POS;
if(b.sign == NEG) a->sign = NEG;


.... instead of `b.sign = a->sign;'?

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

Nov 14 '05 #2
Eric Sosman wrote:
[snip]

One additional remark: Why write
if(b.sign == POS) a->sign = POS;
if(b.sign == NEG) a->sign = NEG;


.... instead of `b.sign = a->sign;'?

You meant a->sign = b.sign, I bet.

Krishanu
Nov 14 '05 #3
Eric Sosman wrote:


One additional remark: Why write

if(b.sign == POS) a->sign = POS;
if(b.sign == NEG) a->sign = NEG;

... instead of `b.sign = a->sign;'?


Because I'm simple-minded. After I get everything working I'll try to
get rough edges like that cleaned up. Thanks for your help.

Marlene
Nov 14 '05 #4
On Wed, 23 Feb 2005 21:37:31 +0530,
Krishanu Debnath <kr******@cal.i nterrasystems.c om> wrote:

Eric Sosman wrote:
[snip]

One additional remark: Why write
if(b.sign == POS) a->sign = POS;
if(b.sign == NEG) a->sign = NEG;


.... instead of `b.sign = a->sign;'?

You meant a->sign = b.sign, I bet.


Is it even remotely possible that b.sign could be neither POS nor NEG,
and what should be done in this case?

Villy
Nov 14 '05 #5
Villy Kruse wrote:
On Wed, 23 Feb 2005 21:37:31 +0530,
Krishanu Debnath <kr******@cal.i nterrasystems.c om> wrote:
Eric Sosman wrote:
One additional remark: Why write
if(b.sign == POS) a->sign = POS;
if(b.sign == NEG) a->sign = NEG;

.... instead of `b.sign = a->sign;'?
You meant a->sign = b.sign, I bet.


Krishanu wins that bet ...
Is it even remotely possible that b.sign could be neither POS nor NEG,
and what should be done in this case?


I thought about that, but decided not to worry about
it for two reasons: First, the obvious intent of the function
was to make a new copy of the `b' struct and its contents,
and second, leaving `a->sign' uninitialized (freshly obtained
from malloc() and hence with indeterminate content) could not
possibly be "right."

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 14 '05 #6
On Thu, 24 Feb 2005 08:44:27 -0500,
Eric Sosman <es*****@acm-dot-org.invalid> wrote:

Is it even remotely possible that b.sign could be neither POS nor NEG,
and what should be done in this case?


I thought about that, but decided not to worry about
it for two reasons: First, the obvious intent of the function
was to make a new copy of the `b' struct and its contents,
and second, leaving `a->sign' uninitialized (freshly obtained
from malloc() and hence with indeterminate content) could not
possibly be "right."


So you could assert (b.sign == POS || b.sign == NET); Perhaps
that is already done earlier in the code. Defensive coding helps
find bugs.
Villy
Nov 14 '05 #7
Villy Kruse wrote:
On Thu, 24 Feb 2005 08:44:27 -0500,
Eric Sosman <es*****@acm-dot-org.invalid> wrote:
Is it even remotely possible that b.sign could be neither POS nor NEG,
and what should be done in this case?


I thought about that, but decided not to worry about
it for two reasons: First, the obvious intent of the function
was to make a new copy of the `b' struct and its contents,
and second, leaving `a->sign' uninitialized (freshly obtained
from malloc() and hence with indeterminate content) could not
possibly be "right."

So you could assert (b.sign == POS || b.sign == NET); Perhaps
that is already done earlier in the code. Defensive coding helps
find bugs.
Villy


Sign is set to POS by bigInit. If by some chance a bigint was not
initialized after it was declared, it would be initialialized by
bigAlloc which looks at initflag and calls bigInit if initflag != 1.
BTW, the assert statement you have written above wouldn't help much. :-)
Speaking of finding bugs, you can see the code for the entire big number
library at:

http://members.shaw.ca/bystander/bignum.html

If you have some time on your hands, take a look at it and see if you
can find the bug in division. Everything else works. If you would like
to email me, you can figure out my email address from the URL.

Marlene
Nov 14 '05 #8

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

Similar topics

7
3022
by: Office Drone | last post by:
I'm a bit confused about memory usage, and for some reason I wasn't able to find a single point-of-call to get the amount of memory available. If we take, for instance, the Windows platform: There is * Virtual memory you can allocate (VirtualAlloc) * Global memory you can allocate (GlobalAlloc) * Local memory you can allocate...
20
2089
by: iouswuoibev | last post by:
When writing a function that manipulates data (for example, a string), is it in principle a good or bad idea to allocate/deallocate memory within that function? For example, I have the following function: char * to_bits(int n, char *s, int b) { int i; if(b == 0) b = 32;
18
3292
by: cs | last post by:
This is the function malloc_m() that should be like malloc() but it should find memory leak, and over bound writing in arrays. How many errors do you see? Thank you ******************************************** /* mallocm.c */ /* funzione di libreria per trattamento della memoria e rilevamento errori */ /* uso: c_compiler malloc.c e...
4
2290
by: NewToCPP | last post by:
Is there any debugging mechanism to find out which part of the code is causing memory leak?
16
2305
by: Pedro Graca | last post by:
I have a file with different ways to write numbers ---- 8< (cut) -------- 0: zero, zilch,, nada, ,,,, empty , void, oh 1: one 7: seven 2: two, too ---- >8 -------------- I wanted to read that file and put it into dynamic memory, like
94
4665
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring that I found inside of a string. Any ideas?
11
1420
by: alexrixhardson | last post by:
Hello guys, Please, be gentle, as I am a C newby :-). I am wondering whether this piece of code leaks memory: somestring = (char *)malloc(initialsize + 1); .... somestring = (char *)realloc(somestring, newsize + 1); .... somestring = somestring + moveforward;
26
2327
by: Ravindra.B | last post by:
I have declared a global variable which is array of pointers and allocated memory for each array variable by using malloc. Some thing similar to below... static char *arr; main() { int i;
33
2849
by: fmassei | last post by:
Hello! I made a short piece of code that I find very useful for debugging, and I wanted to ask you if it is correct, somehow acceptable or if I simply reinvented the wheel. To deal with some bad bugs caused by memory leaks I ended up with this simple solution: I made one header file that, when included, replaces the...
0
7664
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...
0
7583
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...
0
7885
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. ...
0
8106
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...
1
7638
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...
0
7948
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...
1
5484
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...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2082
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

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.