473,748 Members | 10,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problems with realloc()

Hi,
I'm writing a program that separates a set of integers into groups and
then quicksort each group individually. However, I'm having problems
with my realloc() function. (Pardon me if the indentation is weird.
There's no preview button here and I can't tell if my indentation is
correct.)

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

#include <time.h>

#define N 10 // number of integers to sort
#define size 2 // number of groups
#define MAX 100 // maximum value of the integers

void quicksort(int a[], int lo, int hi)
{
int h, l, p, t;

if (lo < hi)
{
l = lo;
h = hi;
p = a[hi];

do {
while ((l < h) && (a[l] <= p))
l = l+1;
while ((h l) && (a[h] >= p))
h = h-1;
if (l < h)
{
t = a[l];
a[l] = a[h];
a[h] = t;
}
} while (l < h);

t = a[l];
a[l] = a[hi];
a[hi] = t;

quicksort(a, lo, l-1);
quicksort(a, l+1, hi);
}
}

int main()
{
int i, j, *length, x[N], **a, *temp;
srand(time(NULL ));

a = (int **)malloc(size * sizeof(int*));
for (i = 0 ; i < size ; i++)
a[i] = (int*)malloc((N/size + 1) * sizeof(int));

length = (int *)malloc(size * sizeof(int));

/* Generate random integers */
printf("Origina l: \n");
for (i = 0 ; i < N ; i++)
{
x[i] = rand() % MAX;
printf("%d ", x[i]);
}
printf("\n\n");

for (j = 0 ; j < N ; j++)
{
for (i = size ; i >= 1 ; i--)
{
if ((double)x[j]/(double)MAX (double)(i-1)/
(double)size)
{
a[i-1][length[i-1]] = x[j];
length[i-1]++;
if (length[i-1] N/size + 1)
{
if ((temp = realloc(a[i-1], sizeof(int) * 2 * (N/size
+ 1))) == NULL)
{
printf("ERROR: realloc failed");
exit(0);
}
a[i-1] = temp;
}
break;
}
}
}

for(i = 0 ; i < size ; i++)
quicksort(a[i],0,length[i]-1);

printf("Sorted: \n");
for(i = 0 ; i < size ; i++)
{
for (j = 0 ; j < length[i] ; j++)
printf("%d ", a[i][j]);
}
printf("\n");

for (i = 0 ; i < length[i] ; i++)
free(a[i]);
free(a);
free(length);
return 0;
}

Everytime the realloc() function is needed, i.e. when the size of any
of the 2 groups has to be increased to more than the original 6
integers, I'll either get the error "Segmentati on Fault", "*** glibc
detected *** realloc(): invalid next size: 0x0000000000502 0c0 ***", or
the value that's supposed to go into the newly created memory, e.g.
a[0][6], becomes 0.

How do I fix this problem?

Thank you.

Regards,
Rayne

Jul 22 '07 #1
7 1851

<la********@yah oo.comwrote in message
news:11******** *************@g 12g2000prg.goog legroups.com...
Hi,
I'm writing a program that separates a set of integers into groups and
then quicksort each group individually. However, I'm having problems
with my realloc() function. (Pardon me if the indentation is weird.
There's no preview button here and I can't tell if my indentation is
correct.)

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

#include <time.h>

#define N 10 // number of integers to sort
#define size 2 // number of groups
#define MAX 100 // maximum value of the integers

void quicksort(int a[], int lo, int hi)
{
int h, l, p, t;

if (lo < hi)
{
l = lo;
h = hi;
p = a[hi];

do {
while ((l < h) && (a[l] <= p))
l = l+1;
while ((h l) && (a[h] >= p))
h = h-1;
if (l < h)
{
t = a[l];
a[l] = a[h];
a[h] = t;
}
} while (l < h);

t = a[l];
a[l] = a[hi];
a[hi] = t;

quicksort(a, lo, l-1);
quicksort(a, l+1, hi);
}
}

int main()
{
int i, j, *length, x[N], **a, *temp;
srand(time(NULL ));

a = (int **)malloc(size * sizeof(int*));
for (i = 0 ; i < size ; i++)
a[i] = (int*)malloc((N/size + 1) * sizeof(int));

length = (int *)malloc(size * sizeof(int));

/* Generate random integers */
printf("Origina l: \n");
for (i = 0 ; i < N ; i++)
{
x[i] = rand() % MAX;
printf("%d ", x[i]);
}
printf("\n\n");

for (j = 0 ; j < N ; j++)
{
for (i = size ; i >= 1 ; i--)
{
if ((double)x[j]/(double)MAX (double)(i-1)/
(double)size)
{
a[i-1][length[i-1]] = x[j];
What is stored in length[i-1]?
length[i-1]++;
if (length[i-1] N/size + 1)
{
if ((temp = realloc(a[i-1], sizeof(int) * 2 * (N/size
+ 1))) == NULL)
{
printf("ERROR: realloc failed");
exit(0);
}
a[i-1] = temp;
}
break;
}
}
}

for(i = 0 ; i < size ; i++)
quicksort(a[i],0,length[i]-1);

printf("Sorted: \n");
for(i = 0 ; i < size ; i++)
{
for (j = 0 ; j < length[i] ; j++)
printf("%d ", a[i][j]);
}
printf("\n");

for (i = 0 ; i < length[i] ; i++)
free(a[i]);
free(a);
free(length);
return 0;
}

Everytime the realloc() function is needed, i.e. when the size of any
of the 2 groups has to be increased to more than the original 6
integers, I'll either get the error "Segmentati on Fault", "*** glibc
detected *** realloc(): invalid next size: 0x0000000000502 0c0 ***", or
the value that's supposed to go into the newly created memory, e.g.
a[0][6], becomes 0.

How do I fix this problem?

Thank you.

Regards,
Rayne

Jul 22 '07 #2
On Jul 22, 2:38 pm, "lancer6...@yah oo.com" <lancer6...@yah oo.com>
wrote:
Hi,
I'm writing a program that separates a set of integers into groups and
then quicksort each group individually. However, I'm having problems
with my realloc() function. (Pardon me if the indentation is weird.
There's no preview button here and I can't tell if my indentation is
correct.)

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

#include <time.h>

#define N 10 // number of integers to sort
#define size 2 // number of groups
#define MAX 100 // maximum value of the integers

void quicksort(int a[], int lo, int hi)
{
int h, l, p, t;

if (lo < hi)
{
l = lo;
h = hi;
p = a[hi];

do {
while ((l < h) && (a[l] <= p))
l = l+1;
while ((h l) && (a[h] >= p))
h = h-1;
if (l < h)
{
t = a[l];
a[l] = a[h];
a[h] = t;
}
} while (l < h);

t = a[l];
a[l] = a[hi];
a[hi] = t;

quicksort(a, lo, l-1);
quicksort(a, l+1, hi);
}

}

int main()
{
int i, j, *length, x[N], **a, *temp;
srand(time(NULL ));

a = (int **)malloc(size * sizeof(int*));
for (i = 0 ; i < size ; i++)
a[i] = (int*)malloc((N/size + 1) * sizeof(int));

length = (int *)malloc(size * sizeof(int));

/* Generate random integers */
printf("Origina l: \n");
for (i = 0 ; i < N ; i++)
{
x[i] = rand() % MAX;
printf("%d ", x[i]);
}
printf("\n\n");

for (j = 0 ; j < N ; j++)
{
for (i = size ; i >= 1 ; i--)
{
if ((double)x[j]/(double)MAX (double)(i-1)/
(double)size)
{
a[i-1][length[i-1]] = x[j];
length[i-1]++;
if (length[i-1] N/size + 1)
{
if ((temp = realloc(a[i-1], sizeof(int) * 2 * (N/size
+ 1))) == NULL)
{
printf("ERROR: realloc failed");
exit(0);
}
a[i-1] = temp;
}
break;
}
}
}

for(i = 0 ; i < size ; i++)
quicksort(a[i],0,length[i]-1);

printf("Sorted: \n");
for(i = 0 ; i < size ; i++)
{
for (j = 0 ; j < length[i] ; j++)
printf("%d ", a[i][j]);
}
printf("\n");

for (i = 0 ; i < length[i] ; i++)
free(a[i]);
free(a);
free(length);
return 0;

}

Everytime the realloc() function is needed, i.e. when the size of any
of the 2 groups has to be increased to more than the original 6
integers, I'll either get the error "Segmentati on Fault", "*** glibc
detected *** realloc(): invalid next size: 0x0000000000502 0c0 ***", or
the value that's supposed to go into the newly created memory, e.g.
a[0][6], becomes 0.

How do I fix this problem?

Thank you.

Regards,
Rayne
The program never initializes the length array. If the idea was to
start with 0, may be you should have used a calloc instead of malloc
for length [].

Jul 22 '07 #3
length[] is the number of each row in matrix a.

Initially, a is a rectangular "size-by-(N/size+1)" matrix. For
example, if size is 2 and N is 10, then a is a 2-by-6 matrix.

As I'm splitting the integers into the appropriate groups (if size =
2, then there are 2 groups), I may end up with a jagged array, i.e.
one group/row a[0][] has 3 integers and the other a[1][] has 7
integers. Then length[0] = 3 and length[1] = 7.

I've initialized length[] with calloc, but I still have the same
problem. I also don't get why length is the problem here.

Jul 22 '07 #4
On Jul 22, 11:10 pm, "lancer6...@yah oo.com" <lancer6...@yah oo.com>
wrote:
length[] is the number of each row in matrix a.
I meant to say length[] is the number of integers in each row of
matrix a.

Jul 22 '07 #5
la********@yaho o.com wrote:
>
On Jul 22, 11:10 pm, "lancer6...@yah oo.com" <lancer6...@yah oo.com>
wrote:
length[] is the number of each row in matrix a.
I meant to say length[] is the number of integers in each row of
matrix a.
/* BEGIN new.c */

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

#include <time.h>

#define N 10 /* number of integers to sort */
#define SIZE 2 /* number of groups */
#define MAX 100 /* maximum value of the integers */

void free_int_2d(int **a, int i);
void quicksort(int a[], int lo, int hi);

int main(void)
{
int i, j, *length, x[N], **a, *temp;

srand(time(NULL ));
a = malloc(SIZE * sizeof *a);
if (a == NULL) {
puts("a == NULL");
exit(EXIT_FAILU RE);
}
length = malloc(SIZE * sizeof *length);
if (length == NULL) {
free_int_2d(a, SIZE);
puts("length == NULL");
exit(EXIT_FAILU RE);
}
for (i = 0 ; i < SIZE ; i++) {
a[i] = NULL;
length[i] = 0;
}
puts("Original: ");
for (i = 0 ; i < N ; i++) {
x[i] = rand() % MAX;
printf("%2d ", x[i]);
}
puts("\n");
for (j = 0 ; j < N ; j++) {
i = SIZE;
while (i-- 0) {
if (x[j] / (double)MAX >= i / (double)SIZE) {
++length[i];
temp = realloc(a[i], length[i] * sizeof *temp);
if (temp == NULL) {
puts("ERROR: realloc failed");
exit(EXIT_FAILU RE);
}
a[i] = temp;
a[i][length[i] - 1] = x[j];
break;
}
}
}
for (i = 0 ; i < SIZE ; i++) {
quicksort(a[i], 0, length[i] - 1);
}
puts("Sorted:") ;
for (i = 0 ; i < SIZE ; i++) {
printf("a[%d] ", i);
for (j = 0 ; j < length[i] ; j++) {
printf("%2d ", a[i][j]);
}
putchar('\n');
}
free_int_2d(a, length[i]);
free(length);
return 0;
}

void quicksort(int a[], int lo, int hi)
{
int h, l, p, t;

if (lo < hi) {
l = lo;
h = hi;
p = a[hi];
do {
while ((l < h) && (a[l] <= p)) {
l = l+1;
}
while ((h l) && (a[h] >= p)) {
h = h-1;
}
if (l < h) {
t = a[l];
a[l] = a[h];
a[h] = t;
}
} while (l < h);
t = a[l];
a[l] = a[hi];
a[hi] = t;
quicksort(a, lo, l-1);
quicksort(a, l+1, hi);
}
}

void free_int_2d(int **a, int i)
{
while (i-- 0) {
free(a[i]);
}
free(a);
}

/* END new.c */
--
pete
Jul 22 '07 #6
pete wrote:
#define N 10 /* number of integers to sort */
#define SIZE 2 /* number of groups */
#define MAX 100 /* maximum value of the integers */
int main(void)
{
int i, j, *length, x[N], **a, *temp;
for (i = 0 ; i < SIZE ; i++) {
printf("a[%d] ", i);
for (j = 0 ; j < length[i] ; j++) {
printf("%2d ", a[i][j]);
}
putchar('\n');
}
free_int_2d(a, length[i]);
Oops!
The above line of code should be

free_int_2d(a, SIZE);

instead.
free(length);
return 0;
}
void free_int_2d(int **a, int i)
{
while (i-- 0) {
free(a[i]);
}
free(a);
}
--
pete
Jul 22 '07 #7
On Sun, 22 Jul 2007 02:38:02 -0700, "la********@yah oo.com"
<la********@yah oo.comwrote:
>Hi,
I'm writing a program that separates a set of integers into groups and
then quicksort each group individually. However, I'm having problems
with my realloc() function. (Pardon me if the indentation is weird.
There's no preview button here and I can't tell if my indentation is
correct.)

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

#include <time.h>

#define N 10 // number of integers to sort
#define size 2 // number of groups
#define MAX 100 // maximum value of the integers

void quicksort(int a[], int lo, int hi)
snip unrelated function
>}

int main()
{
int i, j, *length, x[N], **a, *temp;
srand(time(NULL ));

a = (int **)malloc(size * sizeof(int*));
Don't cast the return from malloc. It only serves to hide undefined
behavior.
for (i = 0 ; i < size ; i++)
a[i] = (int*)malloc((N/size + 1) * sizeof(int));
Are you sure that all groups will have the same number of elements?
>
length = (int *)malloc(size * sizeof(int));
length now points to a space large enough to hold 2 int. However,
neither int has been assigned a value. They are both indeterminate.

You should always check malloc for success.
>
/* Generate random integers */
printf("Origina l: \n");
for (i = 0 ; i < N ; i++)
{
x[i] = rand() % MAX;
printf("%d ", x[i]);
}
printf("\n\n");

for (j = 0 ; j < N ; j++)
{
for (i = size ; i >= 1 ; i--)
{
if ((double)x[j]/(double)MAX (double)(i-1)/
(double)size )
You only need one cast in each division expression.
{
a[i-1][length[i-1]] = x[j];
length[i-1] is still indeterminate. This statement invokes undefined
behavior. From the standard point of view, everything that happens
after this point unconstrained.

From a practical point of view, length[i-1] probably evaluates to a
value out of range for a[i-1] so you end up overflowing the allocated
area. On many systems, this has the effect of stepping on data that
the allocation routines use to keep track of dynamic allocations.
length[i-1]++;
if (length[i-1] N/size + 1)
{
if ((temp = realloc(a[i-1], sizeof(int) * 2 * (N/size
+ 1))) == NULL)
And when realloc tries to use this corrupted data, it gets very
confused.
{
printf("ERROR: realloc failed");
exit(0);
}
a[i-1] = temp;
}
break;
}
}
}

for(i = 0 ; i < size ; i++)
quicksort(a[i],0,length[i]-1);

printf("Sorted: \n");
for(i = 0 ; i < size ; i++)
{
for (j = 0 ; j < length[i] ; j++)
printf("%d ", a[i][j]);
}
printf("\n");

for (i = 0 ; i < length[i] ; i++)
This is wrong. i should run from 0 to size. Each a[i] does point to
length[i] int but you only free the a[i], not each int it points to.

size is 2. length points to 2 int. length[1] could be 4. When i is
1, you free a[1] and increment i to 2. length[2] doesn't exist. More
undefined behavior.
free(a[i]);
free(a);
free(length);
return 0;
}

Everytime the realloc() function is needed, i.e. when the size of any
of the 2 groups has to be increased to more than the original 6
integers, I'll either get the error "Segmentati on Fault", "*** glibc
detected *** realloc(): invalid next size: 0x0000000000502 0c0 ***", or
the value that's supposed to go into the newly created memory, e.g.
a[0][6], becomes 0.


Remove del for email
Jul 22 '07 #8

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

Similar topics

12
2942
by: Michael | last post by:
How would I go about shrinking the buffer that was allocated with new, or expanding it in place? I basically need a realloc equivalent for new. Thanks in advance. Michael
9
2357
by: mordac | last post by:
Hi, writing a heap ADT, need to handle insertion into the heap when it is full. Attempting to use realloc to do this, but realloc is changing the contents of my heap! The following is my incHeapSize function, which is supposed to increase the malloced space for an integer array by 1: Heap incHeapSize(Heap aHeap) { int* tempHeap; aHeap->maxSize++; tempHeap = realloc(aHeap->heapArray, aHeap->maxSize);
12
1711
by: Franz | last post by:
Greetings, I have created the following types: typedef struct _tbl_certificate{ int cert_id; char *cert_name; }tbl_certificate; typedef struct _cameraObj{ tbl_camera camera;
7
2930
by: Marlene Stebbins | last post by:
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;
86
4143
by: Walter Roberson | last post by:
If realloc() finds it necessary to move the memory block, then does it free() the previously allocated block? The C89 standard has some reference to undefined behaviour if one realloc()'s memory that was freed by realloc(), but the only way explicitly mentioned in the C89 standard to free memory via realloc() is to realloc() it down to 0 bytes. I had always assumed it would automatically free the previous memory, but is the behaviour...
28
3876
by: bwaichu | last post by:
Is it generally better to set-up a buffer (fixed sized array) and read and write to that buffer even if it is larger than what is being written to it? Or is it better to allocate memory and realloc it for the size of the what is being written each time? In other words, what is the decision factor between deciding to use a fixed size buffer or allocating memory space and reallocing the size? I don't think the code below is optimal...
18
1611
by: hyperboogie | last post by:
Hello all I'm pretty new to C, so please accept my apologies in advance :-) I'm trying to allocate space for an array of pointers to strings (which are accepted as ellipses) inside a while loop, and after the allocation, when i "assert" the allocation, the assertion fails!!! void printStrings(s1, ...){ //ellipses function ....
4
3508
by: Kenneth Brody | last post by:
I looked at my copy of n1124, and I didn't see anything about this particular situation... What happens if you realloc() to a size of zero? Implementations are allowed to return NULL on malloc(0), and realloc() says it reutrns NULL on failure. (And, on failure, the old pointer has not been freed.) Is it possible for an implementation to return NULL for realloc(ptr,0)
9
3808
by: Francois Grieu | last post by:
When running the following code under MinGW, I get realloc(p,0) returned NULL Is that a non-conformance? TIA, Francois Grieu #include <stdio.h> #include <stdlib.h>
0
8989
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
9537
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
9319
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
9243
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
6795
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
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
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
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
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.