0

My code is not putting the text file data into line on the second pass of the while loop, and any subsequent pass. I'm sure it's a silly error but I cannot find it.

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

 FILE *fr;
 char *line,*word,*vali;
 ssize_t read;
 int i=0,sum=0,len =0,flag=0;
 const char delim[2]=" ";


 int main(int argc, char* argv[])
 {

     line = (char *)malloc(sizeof(&len)); 
     word = (char *)malloc(sizeof(&len));
     vali = (char *)malloc(sizeof(&len));

     fr = fopen(argv[1], "r");
     if(fr==NULL)
     {
         exit(EXIT_FAILURE);
     }
     while ((read = getline(&line, &len, fr)) != -1)
     {
         printf("line is %s\n", line );
         fscanf(fr,"%s%*[^\n]",word);           

         printf("%s ", word);
         vali=strtok(line, delim);
         while(vali != NULL)
         {
             sum=sum+atoi(vali);
             vali = strtok(NULL, delim);
         }
         printf("%d\n", sum);
         sum=0;
         vali=" ";
         len = strlen(line);
    }
    fclose(fr);
    if (line)
        free(line);
    return 0;
 }
Paco Abato
  • 3,920
  • 4
  • 31
  • 54
Barney Chambers
  • 2,720
  • 6
  • 42
  • 78

1 Answers1

2

If len is some integral type containing the desired length of the first line, then:

    &len

Has type pointer-to-integer, and

    sizeof(&len)

Returns the size of a pointer (8 bytes on most 64 bit systems) and

    malloc(sizeof(&len))

Allocates only 8 bytes of memory (or whatever pointer size is on your system).

This is probably at least part of the issue.

Barry Gackle
  • 829
  • 4
  • 17