#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2014
    Posts
    1
    Rep Power
    0

    Segmentation fault.


    In Below code am getting Segmentation fault, i am unable to debug, please help.

    #include<stdio.h>

    char fun(char *d, char *s)
    {

    while(*d != '\0')
    {
    d++;
    if(*d == '\0')
    {
    while(*s != '\0')
    {
    *d=*s;
    d++;
    s++;
    }
    }
    }
    *d = '\0';
    printf("%s",d);
    return 0;
    }

    int main()
    {
    char (*fp)(char *, char *) = fun;

    (*fp)("Function","Pointer");

    return 0;
    }
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    Access violation because you are trying to write to read-only memory.

    "Function" and "Pointer" are string literals. They are created in an area of your program's memory space that is designated as read-only (a similar read-only area is where your program's own code resides). You may read from it, but you may not write to it.

    Try declaring two char arrays which you initialize with those string literals. Then make that function call passing those two char arrays and see what happens.
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    "Function" is a fixed length string. You've tried to write to out of bound memory locations. Well, actually I think it's more seriously wrong than that. Because your copy loop is nested and you've overrun the array bound the loop won't necessarily end just because you're done with s. This puppy will keep searching its allotted space until it seg faults. And that's why maybe the run time is a little long before that event. Hence:
    Code:
    #include<stdlib.h>
    #include<stdio.h>
    
    char fun(char *d, char *s, size_t n) {
      size_t i = 0;
      while((i < n) && *d)
        d++, ++i;
      while((i < n) && *s)
        *d++ = *s++, ++i;
      if (i < n)
        *d = 0;
      else {
        fputs("\nIn fun: buffer too small\n", stderr);
        exit(EXIT_FAILURE);
      }
      return 0;
    }
    
    int main() {
      char result[999];
      char (*fp)(char *, char *, size_t) = fun;
      result[0] = 0;
      (*fp)(result, "Function", 100);
      (*fp)(result, "Pointer", 200);
      puts(result);
      (*fp)(result, "Pointer", 1);
      return EXIT_SUCCESS;
    }
    Last edited by b49P23TIvg; January 9th, 2014 at 09:27 AM.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo