473,395 Members | 1,464 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

using realloc multiple times question...

Hello,

I am trying to use realloc multiple times to extend an array of
doubles but unfortunatly it keeps failing. I think I am mixing up the
size to which the old memory block needs to be extended. So if it's
already 128 in size it needs to be realloc'd to (ORIGSIZE + NEWSIZE)
right ? I have provided a small example below, maybe that will make my
describtion somewhat clearer...

Thank you for any suggestions..

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

#define MAXLINE 1024
#define CHUNK 128

int main(void) {
char line[MAXLINE];
double num = 0.0;
double *array = NULL;
double *tmp = NULL;
int idx = 0;
int trck = 0;

array = malloc(CHUNK * sizeof(double));
if(array == NULL) {
fprintf(stderr, "malloc error \n");
return 1;
}

while(fgets(line, MAXLINE, stdin) != NULL) {
num = strtod(line, (char **)NULL);
array[idx++] = num;
trck++;

if(trck == CHUNK) {
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));
if(tmp != NULL) {
array = tmp;
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}

return 0;
}
Dec 16 '05 #1
7 3740

Mischa wrote:
Hello,

I am trying to use realloc multiple times to extend an array of
doubles but unfortunatly it keeps failing. I think I am mixing up the
size to which the old memory block needs to be extended. So if it's
already 128 in size it needs to be realloc'd to (ORIGSIZE + NEWSIZE)
right ? I have provided a small example below, maybe that will make my
describtion somewhat clearer...

Thank you for any suggestions..

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

#define MAXLINE 1024
#define CHUNK 128

int main(void) {
char line[MAXLINE];
double num = 0.0;
double *array = NULL;
double *tmp = NULL;
int idx = 0;
int trck = 0; array = malloc(CHUNK * sizeof(double));
if(array == NULL) {
fprintf(stderr, "malloc error \n");
return 1;
}
that's a bit verbose for my taste - could have been

if(!(array = malloc(CHUNK*sizeof *array))) {
perror("malloc"); /* this way it'll tell you why malloc failed */
exit(1);
}
while(fgets(line, MAXLINE, stdin) != NULL) {
num = strtod(line, (char **)NULL);
array[idx++] = num;
trck++;
what's trck for?
if(trck == CHUNK) {
....oh - you should really be tracking size and capacity, and assigning
capacity each time you realloc
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));
if you're doing it this way, you'll need to reset trck to 0. but see
above for a better way to keep track of things
if(tmp != NULL) {
array = tmp;
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}

return 0;
}


Dec 16 '05 #2
Mischa wrote:
it needs to be realloc'd to (ORIGSIZE + NEWSIZE) right ?
correct
<snip>

while(fgets(line, MAXLINE, stdin) != NULL) {
num = strtod(line, (char **)NULL);
array[idx++] = num;
trck++;

if(trck == CHUNK) {
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));
if(tmp != NULL) {
array = tmp;
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}


Either you if statement is logically wrong or you forgot to reset trck:

/*** change to >=, this is why you didn't catch your bug ***/
if(trck >= CHUNK) {
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));
if(tmp != NULL) {
array = tmp;
trck = 0; /*** reset trck here otherwise the next time round
*** it will always be larger than CHUNK
***/
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}

Personally, I'd prefer writing something like:

if(idx >= total_size) {
tmp = realloc(array, (total_size + CHUNK) * sizeof(double));
if(tmp != NULL) {
total_size += CHUNK;
} else {
perror("realloc");
free(array);
return 1;
}
}
}

Dec 16 '05 #3
Mischa wrote:
it needs to be realloc'd to (ORIGSIZE + NEWSIZE) right ?
correct
<snip>

while(fgets(line, MAXLINE, stdin) != NULL) {
num = strtod(line, (char **)NULL);
array[idx++] = num;
trck++;

if(trck == CHUNK) {
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));
if(tmp != NULL) {
array = tmp;
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}


Either you if statement is logically wrong or you forgot to reset trck:

/*** change to >=, this is why you didn't catch your bug ***/
if(trck >= CHUNK) {
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));
if(tmp != NULL) {
array = tmp;
trck = 0; /*** reset trck here otherwise the next time round
*** it will always be larger than CHUNK
***/
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}

Personally, I'd prefer writing something like:

if(idx >= total_size) {
tmp = realloc(array, (total_size + CHUNK) * sizeof(double));
if(tmp != NULL) {
array = tmp;
total_size += CHUNK;
} else {
perror("realloc");
free(array);
return 1;
}
}
}

Dec 17 '05 #4
Mischa wrote:
it needs to be realloc'd to (ORIGSIZE + NEWSIZE) right ?
correct
<snip>

while(fgets(line, MAXLINE, stdin) != NULL) {
num = strtod(line, (char **)NULL);
array[idx++] = num;
trck++;

if(trck == CHUNK) {
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));
if(tmp != NULL) {
array = tmp;
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}


Either you if statement is logically wrong or you forgot to reset trck:

/*** change to >=, this is why you didn't catch your bug ***/
if(trck >= CHUNK) {
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));
if(tmp != NULL) {
array = tmp;
trck = 0; /*** reset trck here otherwise the next time round
*** it will always be larger than CHUNK
***/
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}

Personally, I'd prefer writing something like:

if(idx >= total_size) {
tmp = realloc(array, (total_size + CHUNK) * sizeof(double));
if(tmp != NULL) {
array = tmp;
total_size += CHUNK;
} else {
perror("realloc");
free(array);
return 1;
}
}
}

Dec 17 '05 #5
In article <9c********************************@4ax.com>,
Mischa <Mi******@provided.com> wrote:
Hello,

I am trying to use realloc multiple times to extend an array of
doubles but unfortunatly it keeps failing. I think I am mixing up the
size to which the old memory block needs to be extended. So if it's
already 128 in size it needs to be realloc'd to (ORIGSIZE + NEWSIZE)
right ? I have provided a small example below, maybe that will make my
describtion somewhat clearer...

Thank you for any suggestions..

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

#define MAXLINE 1024
#define CHUNK 128

int main(void) {
char line[MAXLINE];
double num = 0.0;
double *array = NULL;
double *tmp = NULL;
int idx = 0;
int trck = 0;
I would write:
int allocated_items = CHUNK;

and forget about trck. What does "trck" mean? allocated_items counts how
many items have been allocated (don't call it allocated_size because
then nobody knows if it is size in elements or in bytes; you can call it
allocated_bytes and make it count bytes).
array = malloc(CHUNK * sizeof(double));
if(array == NULL) {
fprintf(stderr, "malloc error \n");
return 1;
}

while(fgets(line, MAXLINE, stdin) != NULL) {
num = strtod(line, (char **)NULL);
array[idx++] = num;
trck++;

if(trck == CHUNK) { if (idx >= allocated_items) {
allocated_items += CHUNK + 1;
tmp = realloc (array, allocated_items * sizeof (double));
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));
if(tmp != NULL) {
array = tmp;
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}

return 0;
}


Try to use variable names that cannot be misunderstood. Try to use
variables that express things as simple as possible. Typically when I
have an array that can be resized I will have one pointer to the array,
one variable "allocated_elements" and one variable "used_elements".
Obviously used_elements counts how many elements are used,
allocated_elements counts how many elements have been allocated.

I wouldn't allocate the array initially; just start with

array = NULL;
used_elements = 0;
allocated_elements = 0;

and increase the size of the array just before another element is
stored.
Dec 17 '05 #6
Mischa wrote:

I am trying to use realloc multiple times to extend an array of
doubles but unfortunatly it keeps failing. I think I am mixing up
the size to which the old memory block needs to be extended. So
if it's already 128 in size it needs to be realloc'd to (ORIGSIZE
+ NEWSIZE) right ? I have provided a small example below, maybe
that will make my describtion somewhat clearer...


You have various suggestions from others. Now I suggest you take a
look at the coding of ggets, which also uses realloc to open up
storage for fgets. See:

<http://cbfalconer.home.att.net/download/ggets.zip>

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Dec 17 '05 #7
Guys thank you for all the great suggestions. It made things clearer
especially regarding the tracking of size instead of counting items.

Thanks..

Mischa

On Sat, 17 Dec 2005 00:40:50 +0000, Christian Bau
<ch***********@cbau.freeserve.co.uk> wrote:
In article <9c********************************@4ax.com>,
Mischa <Mi******@provided.com> wrote:
Hello,

I am trying to use realloc multiple times to extend an array of
doubles but unfortunatly it keeps failing. I think I am mixing up the
size to which the old memory block needs to be extended. So if it's
already 128 in size it needs to be realloc'd to (ORIGSIZE + NEWSIZE)
right ? I have provided a small example below, maybe that will make my
describtion somewhat clearer...

Thank you for any suggestions..

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

#define MAXLINE 1024
#define CHUNK 128

int main(void) {
char line[MAXLINE];
double num = 0.0;
double *array = NULL;
double *tmp = NULL;
int idx = 0;
int trck = 0;


I would write:
int allocated_items = CHUNK;

and forget about trck. What does "trck" mean? allocated_items counts how
many items have been allocated (don't call it allocated_size because
then nobody knows if it is size in elements or in bytes; you can call it
allocated_bytes and make it count bytes).
array = malloc(CHUNK * sizeof(double));
if(array == NULL) {
fprintf(stderr, "malloc error \n");
return 1;
}

while(fgets(line, MAXLINE, stdin) != NULL) {
num = strtod(line, (char **)NULL);
array[idx++] = num;
trck++;

if(trck == CHUNK) {

if (idx >= allocated_items) {
allocated_items += CHUNK + 1;
tmp = realloc (array, allocated_items * sizeof (double));
tmp = realloc(array, (idx + CHUNK + 1) * sizeof(double));


if(tmp != NULL) {
array = tmp;
} else {
fprintf(stderr, "realloc error\n");
free(array);
return 1;
}
}
}

return 0;
}


Try to use variable names that cannot be misunderstood. Try to use
variables that express things as simple as possible. Typically when I
have an array that can be resized I will have one pointer to the array,
one variable "allocated_elements" and one variable "used_elements".
Obviously used_elements counts how many elements are used,
allocated_elements counts how many elements have been allocated.

I wouldn't allocate the array initially; just start with

array = NULL;
used_elements = 0;
allocated_elements = 0;

and increase the size of the array just before another element is
stored.

Dec 17 '05 #8

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

Similar topics

20
by: Jonas | last post by:
Hi, I'm 99 % sure that Standard C guarantees to do a memory move inside realloc() in case the new, returned memory block (address) is different than the original one. Can any C expert confirm...
86
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...
5
by: James S. Singleton | last post by:
Thanks to everybody who provided an answer to my previous question on this. I am trying to grasp the nitty-gritty details of this, and I am having difficulties understanding some of the issues...
28
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...
19
by: ivan.leben | last post by:
Let's say I have a piece of allocated memory which I want to expand and reuse if possible or allocate in a different part of RAM if resizing is not possible, however, in the latter case I don't...
2
by: solanki.chandrakant | last post by:
hi i have fedora linux 4 and i have simple realloc program which i am included here... plz help me to overcome the realloc to pointer to character variable. The program working 2 times but more...
37
by: ravi.cs.2001 | last post by:
Hi all, I m relatively new to C. I have few queries related to malloc(): #1. When we perform malloc(), the memory allocated dynamically comes from the heap area of the process in concern....
4
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...
1
by: Richard Harter | last post by:
On Fri, 27 Jun 2008 09:28:56 -0700 (PDT), pereges <Broli00@gmail.comwrote: There are some obvious questions that should be asked, e.g., is the contents of your array already sorted as your...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...
0
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...

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.