ejlynch
03-09-2004, 07:05 AM
typedef struct ntperror{
char hostname[16];
int errortype;
}ntperror_t;
main
ntperror_t *r_errptr = NULL;
storederrs = readErrorFile(r_errptr,conf);
int readErrorFile(ntperror_t *read_errptr,FILE *conf)
{
int errors_read = 0;
ntperror_t *tmp_err = NULL;
//temporary pointer used by fread
if ( ( tmp_err = (ntperror_t *)malloc(sizeof(ntperror_t)) ) == NULL) {
perror("malloc:");
}
//read in contents of the stored errors from the configuration
while(fread(tmp_err,sizeof(ntperror_t),1,conf) > 0)
{
errors_read++;
//for the first error that is stored allocate memory for 1 element
if (errors_read == 1){
if ( (read_errptr = (ntperror_t *) malloc( sizeof(ntperror_t) )) == NULL) {
perror("malloc");
}
}
//resize memory area for one more element
else{
if ( (read_errptr = (ntperror_t *)realloc(read_errptr, sizeof(ntperror_t) * errors_read)) == NULL) {
perror("realloc");
}
}
//copy memory pointed to by the temporary pointer into an array
memcpy(&read_errptr[errors_read-1],tmp_err,sizeof(ntperror_t));
}
printf("Errors read from file = %d\n",errors_read);
free(tmp_err);
return errors_read;
}
The problem is that r_errptr is NULL in main after I call the function readErrorFile. Inside the function r_errptr points to the first element of an array of ntperror_t which are structures and works perfectly
How can I allocate memory inside a function that will exist in the main.
char hostname[16];
int errortype;
}ntperror_t;
main
ntperror_t *r_errptr = NULL;
storederrs = readErrorFile(r_errptr,conf);
int readErrorFile(ntperror_t *read_errptr,FILE *conf)
{
int errors_read = 0;
ntperror_t *tmp_err = NULL;
//temporary pointer used by fread
if ( ( tmp_err = (ntperror_t *)malloc(sizeof(ntperror_t)) ) == NULL) {
perror("malloc:");
}
//read in contents of the stored errors from the configuration
while(fread(tmp_err,sizeof(ntperror_t),1,conf) > 0)
{
errors_read++;
//for the first error that is stored allocate memory for 1 element
if (errors_read == 1){
if ( (read_errptr = (ntperror_t *) malloc( sizeof(ntperror_t) )) == NULL) {
perror("malloc");
}
}
//resize memory area for one more element
else{
if ( (read_errptr = (ntperror_t *)realloc(read_errptr, sizeof(ntperror_t) * errors_read)) == NULL) {
perror("realloc");
}
}
//copy memory pointed to by the temporary pointer into an array
memcpy(&read_errptr[errors_read-1],tmp_err,sizeof(ntperror_t));
}
printf("Errors read from file = %d\n",errors_read);
free(tmp_err);
return errors_read;
}
The problem is that r_errptr is NULL in main after I call the function readErrorFile. Inside the function r_errptr points to the first element of an array of ntperror_t which are structures and works perfectly
How can I allocate memory inside a function that will exist in the main.