1

I keep running into a problem with reading values of a struct array, where I keep getting a segmentation fault. Here is the code:

int main() 
{
    /* Get PATH Environment Variable */
    char *pathv[MAX_PATHS];
    char cmd_line[MAX_ARGS];
    struct command_t cmd[3];         //THIS IS THE STRUCT ARRAY
    size_t len = 0;

    /* Parse The Path */
    ParsePath(pathv);

    while(1) {

        /* Print Continuous Prompt */
        PrintPrompt();

        /* Read Command Line & Parse It */
        ReadCommand(cmd_line);

        ParseCommand(cmd_line, cmd);    //PASSING IT TO THIS METHOD
    }

    return 0;
}



int ParseCommand(char *buffer, struct command_t *cmd)
{
    char *name = "Test";
    cmd[0].name;  //IF THIS IS COMMENTED OUT AND THE OTHER LINE AS WELL, PROGRAM RUNS
    printf("%s\n", cmd[0].name); //FINE....THESE TWO LINES CAUSE SEG. FAULT
}

struct command_t {
    char *name;
    int argc;
    char *argv[MAX_ARGS];
};

What am I doing wrong? Your help is greatly appreciated.

3
  • where do you assign to cmd[0].name? Commented Oct 20, 2013 at 18:05
  • 2
    You might also like to show us the definition of struct command_t. Commented Oct 20, 2013 at 18:05
  • Sorry, I just added my struct code. This struct is in a separate header file! Commented Oct 20, 2013 at 18:19

2 Answers 2

2

You never initialize cmd nor write any data. Accessed uninitialized data is undefined behavior in C so yes it is valid to crash. You need to write something into cmd[0].name before reading from it.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm an idiot. I found out what the problem was...I forgot to put = name...WOW. Sorry guys! Thank you.
1

In C, when you declare a variable without assigning a value to it doesn't mean it is empty. It may point to memory garbage from stuff that was ran previously.

Your attempt to printf() whats in cmd[0].name without initializing it can be catastrophic.

You should initialize each variable in your struct before trying to access its value, or at least zero-fill everything in order to make it safe to read:

memset(cmd, 0, sizeof(*cmd) * 3);

2 Comments

Isn't zero-filling memset(cmd, sizeof(*cmd), 0)?
@mLstudent33 Not quite, but yes, forgot a parameter there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.