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;
 }
11
  • 5
    malloc(sizeof(&len)). This doesn't look correct. What is len? It looks like you are allocating space for a pointer only. Commented May 11, 2015 at 8:56
  • 1
    What len is defined as and initialized as? Commented May 11, 2015 at 8:56
  • 1
    Show the full program along with the contents of the file. Also, indent the code properly. Commented May 11, 2015 at 8:58
  • 2
    Standard Warning : Please do not cast the return value of malloc() and family in C. Commented May 11, 2015 at 8:59
  • 1
    What are len, line, word, vali defined as? We could assume something and fix but, thats not the way this works. Please make sure that you put the code that can be compiled. Commented May 11, 2015 at 9:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.