K
kfaeqsuvty
Hello, ....
I have a question regarding realloc() .
Is it possible to ``savely'' realloc() a pointer array
within a structure which is previously allocated by
malloc ?
When I try the c code as listed in the addtree() function
below, it works one time, but fails the other time a.k.a. buggy.
I tried to find some answers online and in some of my books but
I couldn't find any regarding this question.
Your info and/or suggestions are appreciated...
/* the tree node */
struct tnode {
char *md5sum; /* md5sum */
char **filenames; /* filenames */
int count; /* number of occurences */
struct tnode *left;
struct tnode *right;
};
struct tnode *addtree(struct tnode *n, char *sum, char *fname) {
int compare = 0;
if(n == NULL) {
n = (struct tnode *)malloc(sizeof(struct tnode));
n->md5sum = NULL;
n->filenames = NULL;
n->count = 0;
n->md5sum = strdup(sum);
n->filenames = (char **)realloc(n->filenames, (n->count + 1) * sizeof(char *));
n->filenames[n->count++] = strdup(fname);
n->left = n->right = NULL;
} else if((compare = strcmp(sum, n->md5sum)) == 0) {
n->filenames = (char **)realloc(n->filenames, (n->count + 1) * sizeof(char *));
n->filenames[n->count++] = strdup(fname);
} else if(compare < 0)
n->left = addtree(n->left, sum, fname);
else
n->right = addtree(n->right, sum, fname);
return n;
}
p.s.
I left out all of the error checking, to make the code
somewhat more readable.
thnkx....
I have a question regarding realloc() .
Is it possible to ``savely'' realloc() a pointer array
within a structure which is previously allocated by
malloc ?
When I try the c code as listed in the addtree() function
below, it works one time, but fails the other time a.k.a. buggy.
I tried to find some answers online and in some of my books but
I couldn't find any regarding this question.
Your info and/or suggestions are appreciated...
/* the tree node */
struct tnode {
char *md5sum; /* md5sum */
char **filenames; /* filenames */
int count; /* number of occurences */
struct tnode *left;
struct tnode *right;
};
struct tnode *addtree(struct tnode *n, char *sum, char *fname) {
int compare = 0;
if(n == NULL) {
n = (struct tnode *)malloc(sizeof(struct tnode));
n->md5sum = NULL;
n->filenames = NULL;
n->count = 0;
n->md5sum = strdup(sum);
n->filenames = (char **)realloc(n->filenames, (n->count + 1) * sizeof(char *));
n->filenames[n->count++] = strdup(fname);
n->left = n->right = NULL;
} else if((compare = strcmp(sum, n->md5sum)) == 0) {
n->filenames = (char **)realloc(n->filenames, (n->count + 1) * sizeof(char *));
n->filenames[n->count++] = strdup(fname);
} else if(compare < 0)
n->left = addtree(n->left, sum, fname);
else
n->right = addtree(n->right, sum, fname);
return n;
}
p.s.
I left out all of the error checking, to make the code
somewhat more readable.
thnkx....