Thread: Help with Segmentation fault - in simple code

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    4

    Help with Segmentation fault - in simple code

    I m trying to execute the below snippet but ending in Seg fault.
    gdb points to line 16 in "while" loop. If I comment out the "stat" at line 12, code runs fine. Does "stat" locks the file that I m trying to access later ?
    Can anyone help reg this ?

    Code:
      1 #include<stdio.h>
      2 #include<stdlib.h>
      3 #include<sys/types.h>
      4 #include <sys/stat.h>
      5
      6 main()
      7 {
      8   FILE *fp;
      9   char *s;
     10   char f[] = "/home/ramchan/bin/C/ram";
     11   struct stat buffer ;
     12   int k = stat( f, &buffer) ;
     13       printf("\nk is %d",k);
     14
     15     fp =  fopen("ram","r");
     16     while(fgets(s,10,fp)!=NULL)
     17     {
     18       printf("\n here");
     19       printf("%s",s);
     20     }
     21   }

  2. #2
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    You didn't allocate any memory for "s". So it points to a random memory location, which it attempts to write to. Result? A segmentation fault, if you're lucky...

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    4
    However, the below code still works, though "s" has not allocated memory.

    Code:
      1 #include<stdio.h>
      2 #include<stdlib.h>
      3 #include<sys/types.h>
      4 #include <sys/stat.h>
      5
      6 main()
      7 {
      8   FILE *fp;
      9   char *s;
     15     fp =  fopen("ram","r");
     16     while(fgets(s,10,fp)!=NULL)
     17     {
     18       printf("\n here");
     19       printf("%s",s);
     20     }
     21   }

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ramchan
    However, the below code still works, though "s" has not allocated memory.
    If it "works", then you are looking at the result of undefined behaviour. EVOEx is right.

    By the way, do not include line numbers when posting source code. It just makes it harder for others to copy and compile your code, should they even have any motivation to do so.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Mar 2009
    Posts
    4
    As far as I understand, its not mandatory to allocate memory as pointed by second snippet. ( Sorry for including line numbers )

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ramchan
    As far as I understand, its not mandatory to allocate memory as pointed by second snippet.
    As I said, you are looking at the result of undefined behaviour. The problem with undefined behaviour is that it works when you test it, but it won't work (e.g., the program crashes) when the customer tests it in front of the boss just when the boss is thinking of who he should fire now that the economy is not doing too well.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > As far as I understand, its not mandatory to allocate memory as pointed by second snippet.
    All memory allocation in C is the responsibility of the programmer (that's YOU).
    If you declare an array, it's YOUR job to make sure you stay in-bounds.
    If you declare a pointer, it's YOUR job to make sure it points to memory, AND that you stay in-bounds.

    The fact that you can do
    char *s;
    gets(s);
    without an IMMEDIATE crash is 100% luck, and 0% skill. Absolutely anything can happen. Unfortunately, the worst thing which can happen is that it can do what you expect. That's bad, because it leads you to believe something is fine, when it really isn't.

    As you've discovered already, making a non-related addition to the code makes it crash. This simply screams BUG!!!

    It's basically like running across a minefield. Sure you get lucky and miss the first couple, but with each passing step, the chances of survival diminish rapidly.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Let me show you an example. Take this program:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    void test1(char *a)
    {
            char *ptr = a;
            strcpy(ptr, "Hello");
    }
    
    void test2(char *b)
    {
            char *ptr;
            strcpy(ptr, "World");
    }
    
    int main()
    {
            char buf1[20] = { 0 }, buf2[20] = { 0 };
    
            test1(buf1);
            test2(buf2);
    
            printf("%s %s!\n", buf1, buf2);
    
            return 0;
    }
    It's a "Hello World!" program, but with a slight bug. Try if you can spot it.

    Whenever this is compiled and ran, anything can happen. However, if you know enough about the compiler and assembly language, you can make a pretty good guess as of what will probably happen here. Still, the result is ALWAYS dependent on the compiler, the compiler version and even the compiler arguments. Let's look at gcc:

    First, standard compilation, no optimization:
    $ gcc -o test test.c
    $ ./test
    World !

    We just got the string "World !" (note the space). Why is that? Because ptr, in test2, is not set and may contain anything. Because in this case it happens to be at the same memory on the stack as the ptr in test1 was when that ran, and that value was never changed. So if we return from the function, the data is actually still in the memory! It's just no longer used. Whenever the uninitialized variable is read, the value is - in this case - the value that happened to be at that memory location. In this case, still a pointer to buf1.
    Again, I can't stress enough that this NEED NOT happen. It will just happen most of the time.

    Now, however, if we enable optimization, gcc will completely get rid of the ptr variable in test1. So we no longer change the memory location and the ptr in test1, and the ptr in test2 contains something entirely different in memory. In my case, not even a valid, writable, pointer:
    $ gcc -O3 -o test test.c
    $ ./test
    Segmentation fault

    If you didn't understand the full reasoning; don't worry. I think I did a bad job explaining. To actually understand it fully, you'll need to know assembly. The important things in this post are the two different behaviours and the fact that these behaviours are completely dependent on my system - although they will probably do something similar on yours.

  9. #9
    Registered User
    Join Date
    Mar 2009
    Posts
    4
    Thanks all. It was a eye opener.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  2. Annoying Segmentation Fault
    By Zildjian in forum C++ Programming
    Replies: 7
    Last Post: 10-08-2004, 02:07 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM
  5. Simple Code, looking for input.
    By Alien_Freak in forum C Programming
    Replies: 3
    Last Post: 03-03-2002, 11:34 AM