简体   繁体   English

将数组的内存分配给char指针

[英]Allocating memory for a array to char pointer

The following piece of code gives a segmentation fault when allocating memory for the last arg. 下一段代码在为最后一个arg分配内存时给出了分段错误。 What am I doing wrong? 我究竟做错了什么? Thanks. 谢谢。

    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++;
    }

Thanks. 谢谢。

You don't reset the value of i after the for loop, so i is equal to n_args when you reach the bottom block. 你不会在for循环后重置i的值,所以当你到达底部块时, i等于n_args Trying to access command[i] at that point accesses uninitialized memory and segfaults. 此时尝试访问command[i]可访问未初始化的内存和段错误。

The real lesson here is not to reuse variables in this manner without a good reason. 这里真正的教训是没有充分理由以这种方式重用变量。 Your code will be more robust and easier to read if you use something other than i in the middle for loop. 您的代码将更加强大和更容易,如果你使用比其他东西可以读i在中间for循环。

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

should become just 应该变得公正

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

because you just want to alloc an array of n_args elements, and 因为你只想分配一个n_args元素数组,和

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

should become: 应成为:

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

to avoid strlen on a null pointer. 避免空指针上的strlen。

对于包含由单个空格分隔的两个参数的行,n_args将为1而不是2.这可能不是您想要的。

I think you have a few funny things going on here (if I'm reading this correctly). 我想你在这里有一些有趣的事情(如果我正确地读这个)。

This block: 这个块:

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

Should be this: 应该是这样的:

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

No need to reallocate command over and over again. 无需一遍又一遍地重新分配command

As for the seg fault though, could be because you are re-using the i variable without resetting it to zero again first. 至于seg故障,可能是因为你重新使用i变量而不是先将它重置为零。

You're throwing away your first arg? 你扔掉了你的第一个arg? Is that intentional? 这是故意的吗? In case it isn't 如果不是

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");
}

You forgot to reset your i index, which reaches outside your allocated array in your code. 您忘记重置您的i索引,该索引在您的代码中到达分配的数组之外。

Try arranging this loop properly: 尝试正确安排此循环:

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

the line "arg=strtok..." does 2 things wrongs: “arg = strtok ...”这两行有两个错误:

  1. Skips the first argument. 跳过第一个参数。
  2. Doesn't check the return code, so if arg==NULL then strlen(arg) will SEGFAULT. 不检查返回码,所以如果arg == NULL则strlen(arg)将为SEGFAULT。

Do this instead: 改为:

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

It is hard to figure out what you are trying to do. 很难弄清楚你想要做什么。

It looks like you are looking at the number of spaces in the command line to see how many command line arguments you have. 看起来您正在查看命令行中的空格数,以查看您拥有的命令行参数的数量。 Are all of your command line args a single character? 你的所有命令行args都是一个字符吗? The malloc is only reserving enough space for one character per arg. malloc只为每个arg一个字符保留足够的空间。

If your args are just one char each: 如果你的args只是一个char:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM