c - Error using malloc -


i pass char ** input main() processinexp() function, pass again processinexp() function getinput() function dynamically allocate on while reading through file.

inside getinput() function input allocated memory when checked, while using in in processinexp() encounters gets runtime error. can issue?

below code:

int getinput(char ** input, const char * filename) {     int numinput = 0;     int i, j;     char c;     char tempinput[100];     file * pfile;     if((pfile = fopen(filename, "r")) == null)     {         printf("cannot read file %s\n", filename);         system("pause");         exit(1);     }     while(!feof(pfile))     {         c = fgetc(pfile);         if(c == '\n') ++numinput;      }     /* printf("%d\n", numinput); */     input = (char**)malloc(numinput * sizeof(char*)); /* #2 malloc input */     rewind(pfile);     for(i = 0; !feof(pfile); ++i)     {         fscanf(pfile, "%[^\n]%*c", tempinput);         /* printf("%s\n", tempinput); */         input[i] = (char*)malloc((strlen(tempinput) + 1) * sizeof(char)); /* #3 malloc input[] */         strcpy(input[i], tempinput);         /* printf("%s\n", input[i]); */ /* #4 print out */         memset(tempinput, 0, sizeof(tempinput));     }     fclose(pfile);     return numinput; } void processinexp(char ** input, char ** output, const char * filename) {     int numformula;     int i;      numformula = getinput(input, filename); /* #1 passing input */     /* printf("%s\n", input[0]); */ /* #5 runtime error */     output = (char**)malloc(numformula * sizeof(char*));     system("pause");      for(i = 0; < numformula; ++i)     {         convertintopost(input[i], output[i]);         printf("%d. %s -> %s", (i + 1), input[i], output[i]);     }  } 

c uses pass-by-value function argument passing. so, inside function getinput(), cannot change variable input , expect change reflected in actual argument, passed function. that, you'll need pointer-to variable passed, in case, need do

   int getinput(char *** input, const char * filename) { //notice * 

and need call like

   char ** inp = null;    getinput(&inp, ..........); 

then, getinput() able allocate memory *input inside function reflected inp.

otherwise, after returning getinput(), actual argument still uninitialized , using further (in case, in for loop in processinexp() function) lead undefined behaviour.

that said, 2 more important things notice,

  1. please see why not cast return value of malloc() , family in c.
  2. check why while ( !feof (file) ) wrong?

Comments