Getting a seg fault

This is a discussion on Getting a seg fault within the C Programming forums, part of the General Programming Boards category; This is driving me nuts! I dont know much about C so I cant find what I am doing wrong ...

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    85

    Getting a seg fault

    This is driving me nuts! I dont know much about C so I cant find what I am doing wrong but I have debugged it to the point that I know where I am getting a Seg. Fault but dont know why:

    Code:
    void parse_string(char input_string[])  
    {
      char *token;
      char *delim = " ";
    
      token = strtok(input_string,delim);
      while (token != NULL)
       {
        token = strtok(NULL, delim);
       }
    
      return 0;
    }                                                                      
    //------------------------
    int main() {
      int x = 0;                       //holds answer from calculations
      char *buf;                       //pointer to where the directory is
      long size;                       //size of the array, which is the directory name
      char *dir;                       //this is the variable that stores the direcory name and then prints it
      char *path;                      //this is the array that will hold the changed directory's name
      char input_string[maxbuf];       //this is the array which will hold the input
      int flag = 1;
      int pipecount = 0;
      
      signal(SIGTSTP, signal_handler);                        //called when the user hit ctrl-z
          printf("mysh$>");
          if ((buf = (char *)malloc((size_t)size)) != NULL)
            dir = getcwd(buf, size);                          //this is the call to get the directory
          printf("%s >", dir);                                //will print the directory
          fgets (input_string, maxbuf, stdin);                //this will get the command the user enters
          parse_string(input_string);                         //tokenizes the command the user enters
    
            if(strcmp(command[0], "cd") == 0);  {              //SEG FAULT HERE!!!!!!
              dir = chdir(path);
              printf("%s%", dir);  }                            //SEG FAULT HERE!!!!!!
            if (strcmp(command[0], "quit" == 0))
              exit(0);
          // else if (strcmp(command[0], "list" == 0)
          //   command[0] = "ls";
          // else if (strcmp(command[0], "type" == 0)
          //   command[0] = "cat";
          // else if (strcmp(command[0], "cls" == 0)
          //   command[0] = "clear";
          // else if (strcmp(command[0], "move" == 0)
          //   command[0] = "mv";
          // else if (strcmp(command[0], "copy" == 0)
          //   command[0] = "cp";
          // else if (strcmp(command[0], "del" == 0)
          //   command[0] = "rm";
          // else if (strcmp(command[0], "=" == 0){
            // x = arith(command);
            // printf("%s", x); }
          // else
          // printf("Bad Command.  Please try again.");
                                                                             
          execvp(command[0], command);                              //execute the commands
    
      return 0;
    }

    Basically I have other things commented because I am trying to just get at least one or two things to work! Ahhhh! ok so this is am implementation of a Shell program. I want to type cd in and have it go back one directory, naturally. Or quit when I type quit in. I can type something in and once I hit enter it seg faults. In the code in my comments it shows where the seg faults occur. Please help! Thanks!

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    I don't see where command is defined. Is it defined as
    Code:
    char *command[N];
    for some N? If so, why do you not allocate memory for these poor pointers to point to?

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    395
    Code:
    if(strcmp(command[0], "cd") == 0);  {              //SEG FAULT HERE!!!!!!
    wild guess: did you check the content of command[0]?
    Code:
    printf("%s%", dir);  }                            //SEG FAULT HERE!!!!!!
    I'm not sure the trailing % is a good idea...

  4. #4
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,650
    Where did "command" come from? What is it?

    Why the ; after the if in the first line here, and the extra % in the printf?
    Code:
    if(strcmp(command[0], "cd") == 0);  {              //SEG FAULT HERE!!!!!!
    dir = chdir(path);
    printf("%s%", dir);  }                            //SEG FAULT HERE!!!!!!

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,494
    Code:
            if(strcmp(command[0], "cd") == 0);  {              //SEG FAULT HERE!!!!!!
              dir = chdir(path);
              printf("%s%", dir);  }                            //SEG FAULT HERE!!!!!!
    Guess what that ; does.

    And who initialises path?
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    void parse_string(char input_string[])  
    {
      char *token;
      char *delim = " ";
    
      token = strtok(input_string,delim);
      while (token != NULL)
       {
        token = strtok(NULL, delim);
       }
    
      return 0;
    }
    I'm pretty sure you want this to fill in your "command" array.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Registered User
    Join Date
    Nov 2006
    Posts
    85

    Seg Fault

    Ok thanks for your help....cant believe I couldnt see the semi-colon! And I did have command in there...dont know why its not in there in this code...I had it defined somewhere else...which was dumb!

    So I tried to fix what you guys were sayin, but now its messed up even more! It doesnt print my directory anymore! it prints crazy letters. Here is my new code, and the output. Thanks!

    Code:
    void parse_string(char input_string[])  //***********************
    {
      char *token;
      char *delim = " ";
    
      token = strtok(input_string,delim);
      while (token != NULL)
       {
        token = strtok(NULL, delim);
       }
    
      return 0;
    }                                                                      //***********************
    //------------------------
    int main() {
      int x = 0;                       //holds answer from calculations
      char *buf;                       //pointer to where the directory is
      long size;                       //size of the array, which is the directory name
      char *dir;                       //this is the variable that stores the direcory name and then prints it
      char *path;                      //this is the array that will hold the changed directory's name
      char input_string[maxbuf];       //this is the array which will hold the input
      char *command[maxbuf];         //holds the parsed string
      int flag = 1;
      int pipecount = 0;
    
      signal(SIGTSTP, signal_handler);                        //called when the user hit ctrl-z
          printf("mysh$>");
          if ((buf = (char *)malloc((size_t)size)) != NULL)
            dir = getcwd(buf, size);                          //this is the call to get the directory
          printf("%s >", dir);                                //will print the directory
          fgets (input_string, maxbuf, stdin);                //this will get the command the user enters
          parse_string(input_string);                         //this will tokenize the command the user enters
    
            if(strcmp(command[0], "cd") == 0)  { //SEG FAULT HERE!!!
              dir = chdir(path);
              printf("%s", dir);  }              //SEG FAULT HERE!!!
            if (strcmp(command[0], "quit" == 0))
              exit(0);
          // else if (strcmp(command[0], "list" == 0)
          //   command[0] = "ls";
          // else if (strcmp(command[0], "type" == 0)
          //   command[0] = "cat";
          // else if (strcmp(command[0], "cls" == 0)
          //   command[0] = "clear";
          // else if (strcmp(command[0], "move" == 0)
          //   command[0] = "mv";
          // else if (strcmp(command[0], "copy" == 0)
          //   command[0] = "cp";
          // else if (strcmp(command[0], "del" == 0)
    //   command[0] = "rm";
          // else if (strcmp(command[0], "=" == 0){
            // x = arith(command);
            // printf("%s", x); }
          // else
          // printf("Bad Command.  Please try again.");
    
          execvp(command[0], command);                                            //will execute the commands
    
      return 0;
    }
    Output:
    Code:
    -bash-3.1$ gcc project2a.c
    project2a.c: In function āarithā:
    project2a.c:27: warning: comparison between pointer and integer
    project2a.c:34: warning: comparison between pointer and integer
    project2a.c:39: warning: comparison between pointer and integer
    project2a.c:44: warning: comparison between pointer and integer
    project2a.c:58:18: warning: character constant too long for its type
    project2a.c: In function āsignal_handlerā:
    project2a.c:58: warning: comparison between pointer and integer
    project2a.c: In function āparse_stringā:
    project2a.c:69: warning: assignment makes pointer from integer without a cast
    project2a.c:72: warning: assignment makes pointer from integer without a cast
    project2a.c:75: warning: āreturnā with a value, in function returning void
    project2a.c: In function āmainā:
    projec¶ >.c: ’’’)EšĮ}šUš assignment makes pointer from integer without a cast
    Ņt+1’Ę ’’’Eš/a.out
    mysh$>
    I know I have a lot of warnings, but I am just trying to fix one thing at a time!


    ****Ok well I am seeing that I am not saving the parsed strings in command so I am working on fixing that now. Anything else you see that I dont?? Thanks!!!
    Last edited by ammochck21; 01-22-2009 at 02:19 PM.

  8. #8
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,494
    Post some of the lines mentioned in the error messages.

    And you shouldn't be running the code while you've still got warnings and errors.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  9. #9
    Registered User
    Join Date
    Nov 2006
    Posts
    85
    I will post the error messages in a second but I noticed that when I put the ; back in after the if statement:
    Code:
    if(strcmp(command[0], "cd") == 0);  { //SEG FAULT HERE!!!
              dir = chdir(path);
              printf("%s", dir);  }
    it prints nice and neat but when I take it out it prints this:
    output:
    Code:
    projec¶ >.c: ’’’)EšĮ}šUš assignment makes pointer from integer without a cast
    Ņt+1’Ę ’’’Eš/a.out
    mysh$>

    so basically since it is not right to have that semi colon there...something else is majorly wrong!

  10. #10
    Registered User
    Join Date
    Nov 2006
    Posts
    85
    Warnings 1,2,3,4: warning: comparison between pointer and integer

    Code:
      if (command[2] == '/') {
    Code:
     else if (command[2] == '*') {
    Code:
     else if (command[2] == '+'){
    Code:
    else if (command[2] == '-'){
    Warning: warning: assignment makes pointer from integer without a cast
    Code:
    token = strtok(input_string,delim);                ***in my parse function
    Code:
     token = strtok(NULL, delim);                         ***in my parse function

  11. #11
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    So command[2] is a string, not a character -- you cannot compare them directly. The strtok warnings mean you forgot to include a header file <string.h>.

  12. #12
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,543
    First, I shall point out to you that these warnings:
    project2a.c:27: warning: comparison between pointer and integer
    project2a.c:58:18: warning: character constant too long for its type
    project2a.c:69: warning: assignment makes pointer from integer without a cast
    ...should really be treated as errors because they will not make your code run as you want.
    So what do they say, then? Let's examine them.

    >>project2a.c:27: warning: comparison between pointer and integer
    Means you are comparing a pointer to an integer.
    Example:
    Code:
    if (command[2] == '/')
    command in the example is pointer to char (char*), and '/' is a char, a string literal.
    That will never yield any good results. It's like comparing apples and oranges.

    >>project2a.c:58:18: warning: character constant too long for its type
    Example:
    Code:
    char c = 300;
    A char cannot hold the value 300; it is too big and will be truncated in some way. Thus it will not store "300", but something else. It will not give you the results you want.

    >>project2a.c:69: warning: assignment makes pointer from integer without a cast
    Example:
    Code:
    int x = 50;
    void* p = x;
    You are assigning the contents of an integer to a pointer. This will never work, since the address 50 is 99% likely NOT to be writable or readable, thus getting you a crash.
    This is undefined. You must store addresses in pointers, either from malloc or by taking the address of a variable.

    And this warning...
    >>project2a.c:75: warning: āreturnā with a value, in function returning void
    While not critical, it is still bad.
    It means you are returning a value from a function that you have specified does not return anything!
    Example:
    Code:
    void foo() { return 10; }
    Return the appropriate type or return nothing at all!

    There's also another bug in the code:
    Code:
    	if (strcmp(command[0], "quit" == 0))
    Should be:
    Code:
    	if (strcmp(command[0], "quit") == 0)
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  3. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 08:27 PM
  4. Pointer To Functions = Seg Fault
    By misplaced in forum C++ Programming
    Replies: 3
    Last Post: 04-05-2005, 08:03 AM
  5. Seg Fault Problem
    By ChazWest in forum C++ Programming
    Replies: 2
    Last Post: 04-18-2002, 03:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21