Click to See Complete Forum and Search --> : C - Allocating memory in a function


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.

mindcooler
03-09-2004, 07:34 AM
If you want readErrorFile() to allocate memory for its argument read_errptr and you want that allocation to "be visible" from the caller, you need to pass a pointer to a pointer.

This code examplifies:


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

struct blah_t
{
int a;
int b;
};

void allocate(struct blah_t** blah)
{
*blah = malloc(sizeof(struct blah_t));

(*blah)->a = 1;
(*blah)->b = 2;
}

int main(void)
{
struct blah_t* blah = NULL;

allocate(&blah);

printf("%i\n", blah->a);
printf("%i\n", blah->b);

free(blah);

return 0;
}


HTH, mindcooler

ejlynch
03-09-2004, 07:42 AM
that did the job... :D

Thanks