M
Marlene Stebbins
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))==NULL)
{
fprintf(stderr, "malloc failed in bigInit()\n");
exit(EXIT_FAILURE);
}
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)))==NULL)
{
fprintf(stderr, "bigAlloc failed\n");
exit(EXIT_FAILURE);
}
return;
}
/* bigint assignment: a = b */
void bigAssign(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;
}
/* 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;
}
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))==NULL)
{
fprintf(stderr, "malloc failed in bigInit()\n");
exit(EXIT_FAILURE);
}
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)))==NULL)
{
fprintf(stderr, "bigAlloc failed\n");
exit(EXIT_FAILURE);
}
return;
}
/* bigint assignment: a = b */
void bigAssign(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;
}
/* 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;
}