Thread: Segfault

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    12

    Angry Segfault

    I've debugged my program, and I just can't figure out what's wrong. So I gave up and will just post my program, hopefully someone can fix it. Probably something to do with pointers, I attempted to free the malloc charArray, even set it to 0 after every convert, same error.

    What this script does is, take 10 arg inputs, and rearrange all there chars in order of ASCII value. However I need to store all 10 of them in separate arrays, for other functions later on which I haven't coded yet.

    I attempted to use multidimensional arrays, but they causes more errors at the start. So I ended up resorting to 10 separate arrays to hold each arg.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc,char *argv[]) {
    
    char * charArray;               //holds shifted input
    char * charArray1, * charArray2, * charArray3, * charArray4, * charArray5, * charArray6, * charArray7, * charArray8, * charArray9, * charArray10; 
    
    //char outputArray[10] = {0};   //holds ascii-sorted output
    int x;
    int y;                          //holds length of input; Dykstras algo, total mount of swaps = n                        
    int z=1;                        //holds current argv
    char a; char b;                 //temp vars, to hold current char [x], and next char [x+1]
    
    
    void sortFunc (char * inputArray)       /* Function to alphabetically/no. order a single input  */
    {
    
    
      for ( x=0; x < (strlen(inputArray)-1); x++ ) {
            if ( ((int)inputArray[x] > (int)inputArray[(x+1)]) && (inputArray[(x+1)] != 0) ) {
                    putchar('-');
                    a = inputArray[x];
                    b = inputArray[(x+1)];
                    inputArray[x] = b;
                    inputArray[(x+1)] = a;
            }       
    
    
      }
      strcpy(charArray, inputArray);
    
    puts("¬");
    }
    
    void argInput() {       /* Function for sorting argv input, then pass it onto function to sort  */
    
       for ( z = 1; z < 11; z++ ) {
            charArray = (char *) malloc(strlen(argv[z])+1);
            strcpy(charArray, argv[z]);             /* Copy argv[1] into charArray  */
    
            /* Maximum amount of swaps, thus this creates complete ascii-ordered char array  */
            for ( y = 0; y < strlen(charArray); y++ ) {
            printf(" | y:%d len:%d |", y, strlen(charArray) );
                    sortFunc(charArray);                    /* Call the function            */
                    printf("%s", charArray); 
            }
    
                    if ( z == 1 ) { strcpy(charArray1, charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray1); }
               else if ( z == 2 ) { strcpy(charArray2, charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray2); }
               else if ( z == 3 ) { strcpy(charArray3, charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray3); }
               else if ( z == 4 ) { strcpy(charArray4, charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray4); }
               else if ( z == 5 ) { strcpy(charArray5, charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray5); }
               else if ( z == 6 ) { strcpy(charArray6, charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray6); }
               else if ( z == 7 ) { strcpy(charArray7, charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray7); }
               else if ( z == 8 ) { strcpy(charArray8, charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray8); }
               else if ( z == 9 ) { strcpy(charArray9, charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray9); }
               else if ( z == 10) { strcpy(charArray10,charArray); printf("Input (argv): %s | Output (shift): %s\n\n", argv[z], charArray10);}
    //              free(charArray);
    //              charArray = 0;                  
    //              strcpy(charArray(z), charArray);
    
       }
    }
    
    //void sortWord() {
    //}
    
    //sortWord();
    argInput();
    
    putchar('\n');
    return 0;
    }



    It's odd. Since it works for the first 2 args, then always fails in the thirds.
    Output:
    Code:
    % ./a.out 54321 54321 54321 54321 54321 54321 54321 54321 54321 54321
    | y:0 len:5 |----¬
    43215 | y:1 len:5 |---¬
    32145 | y:2 len:5 |--¬
    21345 | y:3 len:5 |-¬
    12345 | y:4 len:5 |¬
    12345Input (argv): 54321 | Output (shift): 12345
    
    | y:0 len:5 |----¬
    43215 | y:1 len:5 |---¬
    32145 | y:2 len:5 |--¬
    21345 | y:3 len:5 |-¬
    12345 | y:4 len:5 |¬
    12345Input (argv): 54321 | Output (shift): 12345
    
    | y:0 len:5 |----¬
    43215 | y:1 len:5 |---¬
    32145 | y:2 len:5 |--¬
    21345 | y:3 len:5 |-¬
    12345 | y:4 len:5 |¬
    Segmentation fault (core dumped)
    Notice the end, it successfully sorts the 3rd arg's ascii values. However fails when around the print function.

    GDB, error (so vague, since I don't know which strcpy and I don't how to change strcpy either, since it works like that):
    Code:
    #0  0x28175a5c in strcpy () from /lib/libc.so.7
    #1  0x28050626 in dlopen () from /libexec/ld-elf.so.1
    #2  0x08048629 in main ()
    -Anyone, mind helping.
    -Just simply copy the C program, and compile it
    -And for test, use these args, if you successfully get all 10 args to print, problem solved:
    ./a.out 154321 54321 54321 54321 54321 54321 54321 54321 54321 54321
    Last edited by astral; 06-18-2011 at 05:48 AM. Reason: Code missing*

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > -And for test, use these args, if you successfully get all 10 args to print, problem solved:
    Well it would help if you posted something we can compile.
    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.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    12
    Quote Originally Posted by Salem View Post
    > -And for test, use these args, if you successfully get all 10 args to print, problem solved:
    Well it would help if you posted something we can compile.
    Fixed, it seemed some code went missing as I copied it.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Oh good, then perhaps you can explain the missing brace at the end of main, and how argInput() gets an argv
    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.

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    12
    Quote Originally Posted by Salem View Post
    Oh good, then perhaps you can explain the missing brace at the end of main, and how argInput() gets an argv
    There is no missing brace. And argInput() gets an argv[] from main, well it successfully grabs the first 3 argv, as shown by the output.

  6. #6
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    FYI: when you are seeking help please do not use compiler-specific features (in your case, nested functions). This only makes it harder for people to help you.

    The problem is (among others) with the fact that charArray1 is never set to a valid memory location but you use it as a destination for a strcpy on line 50, same probably goes with alot of other pointers. You should also avoid magic numbers (the number 11 in a loop of yours for intance, use argc instead).

    Did you enable debugging symbols when compiling (on gcc its the -g option), because this gave a filename and a linenumber of the call that caused the segfault.
    Last edited by Shakti; 06-18-2011 at 06:30 AM.

  7. #7
    Registered User
    Join Date
    Jun 2011
    Posts
    12
    Quote Originally Posted by Shakti View Post
    FYI: when you are seeking help please do not use compiler-specific features (in your case, nested functions). This only makes it harder for people to help you.

    The problem is (among others) with the fact that charArray1 is never set to a valid memory location but you use it as a destination for a strcpy on line 50, same probably goes with alot of other pointers. You should also avoid magic numbers (the number 11 in a loop of yours for intance, use argc instead).

    Did you enable debugging symbols when compiling (on gcc its the -g option), because this gave a filename and a linenumber of the call that caused the segfault.
    Thanks, initializing each charArray(1-10) with a memory location that fixed it. I still don't understand how the first 2 charArrays (1,2) were able to function correctly, then always crashed at 3 (since all 10 charArrays are exactly the same)?

  8. #8
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    OMG nested functions?! Where does one find a compiler that can accept that?

    I love the irony of this line (and the corresponding if-else chain):
    Code:
    char * charArray1, * charArray2, * charArray3, * charArray4, * charArray5, * charArray6, * charArray7, * charArray8, * charArray9, * charArray10;
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > OMG nested functions?! Where does one find a compiler that can accept that?
    Great, massively non-standard C, and crappy indentation to go along with it.
    May as well have just pulled it from IOCCC

    gcc will compile it, if you don't put too many checks in.
    Code:
    $ gcc -std=c99 -W -Wall -pedantic baz.c
    baz.c: In function ‘main’:
    baz.c:18: warning: ISO C forbids nested functions
    baz.c: In function ‘sortFunc’:
    baz.c:19: warning: comparison between signed and unsigned integer expressions
    baz.c: In function ‘main’:
    baz.c:33: warning: ISO C forbids nested functions
    baz.c: In function ‘argInput’:
    baz.c:39: warning: comparison between signed and unsigned integer expressions
    baz.c: In function ‘main’:
    baz.c:5: warning: unused parameter ‘argc’
    Anyway, consider this as well.
    Code:
    $ gcc -g baz.c
    $ gdb ./a.out 
    GNU gdb (GDB) 7.1-ubuntu
    Copyright (C) 2010 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "i486-linux-gnu".
    For bug reporting instructions, please see:
    <http://www.gnu.org/software/gdb/bugs/>...
    Reading symbols from /home/sc/work/a.out...done.
    (gdb) run 54321 54321 54321 54321 54321 54321 54321 54321 54321 54321
    Starting program: /home/sc/work/a.out 54321 54321 54321 54321 54321 54321 54321 54321 54321 54321
     | y:0 len:5 |----¬
    43215 | y:1 len:5 |---¬
    32145 | y:2 len:5 |--¬
    21345 | y:3 len:5 |-¬
    12345 | y:4 len:5 |¬
    
    Program received signal SIGSEGV, Segmentation fault.
    *__GI_strcpy (dest=0x283ff4 "|]\025", src=0x804b008 "12345") at strcpy.c:40
    40    strcpy.c: No such file or directory.
        in strcpy.c
    (gdb) bt
    #0  *__GI_strcpy (dest=0x283ff4 "|]\025", src=0x804b008 "12345") at strcpy.c:40
    #1  0x080486d9 in argInput () at baz.c:46
    #2  0x080485e1 in main (argc=11, argv=0xbffff4a4) at baz.c:89
    (gdb) kill
    Kill the program being debugged? (y or n) y
    (gdb) quit
    Compile with -g, so you get more information from the stack trace.
    In my copy of the code, line 46 (where strcpy is called with a garbage pointer) is at
    Code:
                if (z == 1) {
                    strcpy(charArray1, charArray);
                    printf("Input (argv): %s | Output (shift): %s\n\n",
                           argv[z], charArray1);
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. another SEGFAULT
    By cerr in forum C Programming
    Replies: 8
    Last Post: 01-14-2010, 11:04 AM
  2. Sometimes segfault, sometimes not
    By jcafaro10 in forum C Programming
    Replies: 18
    Last Post: 04-07-2009, 06:53 PM
  3. segFault
    By Fox101 in forum C Programming
    Replies: 1
    Last Post: 04-10-2008, 12:00 AM
  4. Segfault
    By oddball in forum C Programming
    Replies: 2
    Last Post: 11-02-2007, 07:53 AM
  5. segfault with gcc, but not with TC
    By koodoo in forum C Programming
    Replies: 15
    Last Post: 04-23-2007, 09:08 AM