Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0

    Segmentation fault


    I'm having trouble with a segmentation fault on this program:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
      int i=0,n=0,a;
      char config[15];
    
      FILE *data;
    
      data = fopen("data.txt","w+");
    
      for(i=0;i<=65535;i++)
         fprintf(data,"%d\n",i);
    
      printf("\nConfiguration: ");
      scanf("%s",config);
      getchar();
    
      while (config[i]!='\n')
        {
          n = n*2+config[i];
          i++;
        }
    
      printf("\nConfiguration is on line %d.\n",n+1);
    
    for (i=1;i<=65536;i++)
      {
        fscanf(data,"%d\n",&a);
    
        if (a == n)
          {
          printf("\nVerification indicates that your configuration is on line %d\n",i);
          fclose(data);    
          return 1;
          }
      }
    }
    I think it comes from "scanf("%s",config);"

    Can anyone help me please? :confused:
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,900
    Rep Power
    481
    Your scanf is certainly bad because it permits array overrun. Use fgets instead. But that's probably not the trouble.


    Code:
      data = fopen("data.txt","w+");
      for(i=0;i<=65535;i++)
        fprintf(data,"%d\n",i);
      /* HERE i has what value?  65536 ****************/
      printf("\nConfiguration: ");
      scanf("%s",config);
      getchar();
      while (config[i]!='\n') {  /* HERE you attempt to access config[65536] *****************/
        n = n*2+config[i];
        i++;
      }
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,175
    Rep Power
    2222
    I also have to wonder whether the file even opened successfully.

    Code:
      FILE *data;
    
      data = fopen("data.txt","w+");
    
      // Missing here is your test of whether the file opened
      // Read the documentation for fopen().  If it succeeds then it returns 
      //      a pointer to the file handle (a FILE*), but if it fails then it returns NULL.
      // What do you thing would happen if you try to use NULL to process a file?
      //  Would you imagine that it might cause the program to crash because you're
      //      trying to access memory that belongs to the OS?  In the Intel processors
      //      I'm familiar with, Location Zero, which is where NULL usually points, is where
      //      the Interrupt Vector Table (IVT).  No self-respecting operating system (which 
      //      obviously does not include MS-DOS) would ever let you get anywhere near the IVT.
      // CORRECTIVE ACTION:  If data is NULL, then report the error and handle it.
      //      However you decide to handle the error, you absolutely must not allow 
      //      the program to try to use that FILE pointer. 
    
      for(i=0;i<=65535;i++)
          // You blithely use data without knowing whether the file actually opened.
           // Do you really enjoy playing Russian Roulette that much?
         fprintf(data,"%d\n",i);
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,175
    Rep Power
    2222
    And stop lying to the compiler.

    C:TEST>gcc -Wall toodd1.c
    toodd1.c: In function `main':
    toodd1.c:40: warning: control reaches end of non-void function

    C:TEST>
    You told the compiler that you would return an int, but then you didn't. Correct that!

    Also, you tried to run that program even though the compiler threw a warning at you. Why are you ignoring warnings? Never ignore warnings!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    Originally Posted by dwise1_aol
    And stop lying to the compiler.


    You told the compiler that you would return an int, but then you didn't. Correct that!

    Also, you tried to run that program even though the compiler threw a warning at you. Why are you ignoring warnings? Never ignore warnings!
    I never get those warnings from the compiler. But anyway problem is solved thanks! I can't believe how stupid and evident my mistake was... :eh:
  10. #6
  11. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,175
    Rep Power
    2222
    What compiler are you using? What settings are you using? Many compilers allow you to turn warnings off or else require you to explicitly turn warnings on. Not turning warnings on and up is a very foolish thing to do. Even more foolish than ignoring warnings.

    How did you solve the problem? There are far more lurkers on these forums than there are participants. Somebody else may be searching for a solution to a similar kind of problem and so would benefit from knowing what the problem turned out to be and what the solution was.


    And remember: Always turn warnings on and up! And never ignore warnings!
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    Originally Posted by b49P23TIvg
    Your scanf is certainly bad because it permits array overrun. Use fgets instead. But that's probably not the trouble.


    Code:
      data = fopen("data.txt","w+");
      for(i=0;i<=65535;i++)
        fprintf(data,"%d\n",i);
      /* HERE i has what value?  65536 ****************/
      printf("\nConfiguration: ");
      scanf("%s",config);
      getchar();
      while (config[i]!='\n') {  /* HERE you attempt to access config[65536] *****************/
        n = n*2+config[i];
        i++;
      }
    This helped me solving my problem. In fact i should have put i = 0 before the while loop...

    I use the command line of ubuntu to compile the programs with command gcc -o.
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    Also I have another question:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
       int i=0,n=0,a;
       char config[18];
    
       printf("\nConfiguration: ");
       fgets(config, sizeof config, stdin);
    
       while (config[i]!='\n')
         {
            if (config[i]=='0')
               a=0;
            else if (config[i]=='1')
               a=1;
            else
               {
               printf("\nError: Enter a correct configuration!\n\n");
               return 0;
               }
            n = n*2 + a;
            i++;
         }
    
       printf("\nConfiguration is on line %d.\n",n+1);
    
       FILE *data;
    
       data = fopen("data.txt","w+b");
    
       if (data == NULL) 
         {
         printf("\nError: Unsuccessful opening of \"data.txt\".\n\n");
         return 0;
         }
    
       for(i=0;i<=65535;i++)
           fprintf(data,"%d\n",i);
    
       rewind(data);
    
       for (i=1;i<=65536;i++)
          {
             fscanf(data,"%d\n",&a);
     
             if (a == n)
                {
                printf("\nVerification indicates that your configuration is on line %d\n\n",i);
                fclose(data);    
                return 1;
                }
          }
    }
    How can i use fgets instead of fscanf (end of code)? Because with fgets i get a string and I need an intenger to compare it with variable n.
  16. #9
  17. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,175
    Rep Power
    2222
    Originally Posted by Toodd
    This helped me solving my problem. In fact i should have put i = 0 before the while loop...
    You also need to test whether fopen succeeded, always.

    Try a little experiment with your "now working" code. Change fopen to try to open a file that doesn't exist; ie, change "data.txt" to something like "nodata.xyz" (assuming that no such file exists). Compile and then run that program. What happens when you try to use a file that doesn't exist?

    Always test the return value of fopen.

    Originally Posted by Toodd
    I use the command line of ubuntu to compile the programs with command gcc -o.
    Did you look at my invocation of gcc?
    C:TEST>gcc -Wall toodd1.c

    That -Wall tells the compiler to turn on all warnings.

    There's also -Werror which treats warnings like errors and doesn't generate an executable if there are warnings. This can be a good thing, because warnings are indications that there's something wrong with your program.

    There's also --pedantic, which I think means that it tests the validity of the code more strictly.

    I always compile with -Wall, without fail. Blinding yourself to problems in your code is very foolhardy and conduct unbefitting a programmer.

    Always turn warnings on and up! Never ignore warnings!
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    Ok.. I'll try to remember that.

    BTW I found the solution of my second question:

    Code:
    for (i=1;i<=65536;i++)
          {
    	fgets(a2,sizeof a2,data); ||a2 is a string||
     
    	if (atoi(a2) == n)
                {
                printf("\nVerification indicates that your configuration is on line %d\n\n",i);
                fclose(data);    
                return 1;
                }
          }
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    I tried to compile with -Wall. This is what I got:

    Code:
    8_2: In function `_fini':
    (.fini+0x0): multiple definition of `_fini'
    BLABLA: first defined here
    8_2: In function `__data_start':
    (.data+0x0): multiple definition of `__data_start'
    BLABLA: first defined here
    8_2: In function `__data_start':
    (.data+0x8): multiple definition of `__dso_handle'
    /usr/lib/gcc/x86_64-linux-gnu/4.6/crtbegin.o:(.data+0x0): first defined here
    8_2:(.rodata+0x0): multiple definition of `_IO_stdin_used'
    BLABLA: first defined here
    8_2: In function `_start':
    (.text+0x0): multiple definition of `_start'
    BLABLA: first defined here
    8_2: In function `_init':
    (.init+0x0): multiple definition of `_init'
    BLABLA: first defined here
    /tmp/cczggn2q.o: In function `main':
    8_2.c:(.text+0x0): multiple definition of `main'
    8_2:(.text+0xe4): first defined here
    BLABLA: multiple definition of `__DTOR_END__'
    8_2:(.dtors+0x8): first defined here
    /usr/bin/ld: error in 8_2(.eh_frame); no .eh_frame_hdr table will be created.
    collect2: ld returned 1 exit status
    Some lines where making trouble (You have included too many images in your signature or in your previous post.) I replaced them by BLABLA:

    I don't understand this...
  22. #12
  23. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,175
    Rep Power
    2222
    What is your source code like? Only what you posted?

    I fired up my laptop in order to run Ubantu (Kosmic Koala) under VMWare Player. With a flashdrive, I transferred your code as posted in Message 1 over to Ubantu and compiled it, then copy-and-pasted the terminal screen to a text file via gedit and saved that file to the flashdrive in order to sneaker-net it back over the WinXp machine that's actually connected to the Internet (my laptop is not authorized network access here at work):
    dwise1@ubuntu:~/Projects$ gcc -Wall toodd1.c
    toodd1.c: In function ‘main’:
    toodd1.c:40: warning: control reaches end of non-void function
    dwise1@ubuntu:~/Projects$
    That junk you see around main were single quotes in terminal.

    I cannot reproduce anything close to the output that you describe.
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    Well then that's a reason for me to not use -Wall... :argh:
  26. #14
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    Now I have another question... Yeah just one more:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
       int i=0,n=0,a;
       int v[65536];
       char config[18];
    
       printf("\nConfiguration: ");
       fgets(config, sizeof config, stdin);
    
       while (config[i]!='\n')
         {
            if (config[i]=='0')
               a=0;
            else if (config[i]=='1')
               a=1;
            else
               {
               printf("\nError: Incorrect configuration!\n\n");
               return 0;
               }
            n = n*2 + a;
            i++;
         }
    
       printf("\nConfiguration is on line %d.\n",n+1);
    
       FILE *data;
    
       data = fopen("data.txt","w+b");
    
       if (data == NULL) 
         {
         printf("\nError: Unsuccessful opening of \"data.txt\".\n\n");
         return 0;
         }
    
       for(i=0;i<=65535;i++)
         {
           v[i]=i;
           fwrite(&v,sizeof (int),65536,data);
         }
    
       rewind(data);
       
       for (i=1;i<=65536;i++)
          {
    	fread(&v,sizeof (int),65536,data);
    
    	if (v[i] == n)
                {
                printf("\nVerification indicates that your configuration is on line %d\n\n",i);
                fclose(data);    
                return 1;
                }
           }
       return 0;
    }
    So this is me trying to make the same program that I did before but with binary files this time. My program completely crashes. I don't know what happen. No error messages nothing from the compiler. IDK what to do.
  28. #15
  29. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,175
    Rep Power
    2222
    Flying blind is not a viable option.

    A lot of that looked like linker (ld) errors. Those should show up even without -Wall. Something else is going on there, which seems to indicate that you've got deeper problems.
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo