M
Mischa
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;
}
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;
}