Memory allocation for an array with char pointer

The following code fragment gives a segmentation error when allocating memory for the last argument. What am I doing wrong? Thank.

    int n_args = 0, i = 0;
    while (line[i] != '\0')
    {
        if (isspace(line[i++]))
            n_args++;
    }

    for (i = 0; i < n_args; i++)
        command = malloc (n_args * sizeof(char*));

    char* arg = NULL;
    arg = strtok(line, " \n");
    while (arg != NULL)
    {
        arg = strtok(NULL, " \n");
            command[i] = malloc ( (strlen(arg)+1) * sizeof(char) );
        strcpy(command[i], arg);
        i++;
    }

Thank.

+3
source share
7 answers

You do not reset the value iafter the loop for, so it iis equal n_argswhen you reach the bottom block. An attempt to access command[i]at this point refers to uninitialized memory and segfaults.

, . , - i for.

+4
for (i = 0; i < n_args; i++)
        command = malloc (n_args * sizeof(char*));

command = malloc (n_args * sizeof(char*))

n_args

while (arg != NULL)
    {
        arg = strtok(NULL, " \n");
        command[i] = malloc ( (strlen(arg)+1) * sizeof(char) );
        strcpy(command[i], arg);
        i++;
    }

:

arg = strtok(NULL, " \n");
while (arg != NULL) {
    command[i] = malloc ( (strlen(arg)+1) * sizeof(char) );
    strcpy(command[i], arg);
    i++;
    arg = strtok(NULL, " \n");
}

strlen .

+2

, , , n_args 1, 2. , , , .

0

, , ( ).

:

for (i = 0; i < n_args; i++)
    command = malloc (n_args * sizeof(char*));

:

    command = malloc (n_args * sizeof(char*));

command .

seg, , , i, .

0

? ?

int n_args = 1;     /* We need one element more than spaces */
int i = 0;
while (line[i])
{
    if (isspace(line[i++]))
        n_args++;
}

command = malloc (n_args * sizeof(char*));

char* arg = NULL;
arg = strtok(line, " \n");
i = 0;        /***** You forgot to reset that value, that was your segfault !!! */
while (arg)
{
    command[i++] = strdup(arg);  /* It does your malloc/strlen/strcpy */
    arg = strtok(NULL, " \n");
}

reset i, .

0

:

 while (arg != NULL)
    {
        arg = strtok(NULL, " \n");
            command[i] = malloc ( (strlen(arg)+1) * sizeof(char) );
        strcpy(command[i], arg);
        i++;
    }

"arg = strtok..." 2 :

  • .
  • , , arg == NULL, strlen (arg) SEGFAULT.

:

 while (arg != NULL)
    {
        command[i] = malloc ( (strlen(arg)+1) * sizeof(char) );
        strcpy(command[i], arg);
        i++;
        arg = strtok(NULL, " \n");
    }
0

, .

, , , . ? Malloc arg.

char :

command = malloc(strlen(line));
i = 0;
j = 0;
while(line[j]) {
   if(!isspace(line[j])){
      command[i++] = line[j];
   }
   j++;
}
0
source

Source: https://habr.com/ru/post/1747067/


All Articles