读取大小为1的Valgrind错误无效

时间:2015-12-04 04:44:11

标签: c malloc valgrind

在我的程序中,函数read_commands只获取2个字符串并将其放入结构Commands并返回填充的结构。
显然我的逻辑有些错误。我收到了错误:

  

读取大小无效1

在valgrind。

typedef struct{  
Command *test  
Command *compile
}Commands;


typedef struct Command{  
char *command;  
struct Command *next;
}Command;

我只是做read_commands("abc", "abc");

我的其余代码:

Commands read_commands(const char *compile_cmds, const char *test_cmds) {
  Commands commands;
  Command *compile, *test;
  int i;              
  if (compile_cmds == NULL || test_cmds == NULL)
     exit(0);

  compile = commands.compile;
  test = commands.test;

  i = 0;
  while (compile_cmds + i != NULL) {
    compile = malloc(sizeof(Command));
    compile->command = malloc(strlen((compile_cmds + i) + 1));
    strcpy(compile->command, compile_cmds + i);
    compile = compile->next;
    i++;
  }
  i = 0;
  while (test_cmds + i != NULL) {
    test = malloc(sizeof(Command));
    test->command = malloc(strlen((test_cmds + i) + 1));
    strcpy(test->command, test_cmds + i);
    test = test->next;
    i++;
  }
  return commands;
}

1 个答案:

答案 0 :(得分:1)

您应该更改参数以接受多个命令,例如

Commands read_commands(const char** compile_cmds, const char** test_cmds)

然后你用:

来称呼它
char* compileCmds[] = { "abc", NULL };
char* testCmds[] = { "abc", NULL };

Commands c = read_commands(compileCmds,testCmds);

同时在你的函数中获取所有“编译”命令:

Commands commands = { NULL, NULL };
...

Command* last = NULL;
for (i = 0; compile_cmds[i] != NULL; ++i)
{
  compile = malloc(sizeof(Command));

  // check if we have added before, or if it is the first compile command
  if (last!=NULL)
  {
    // last command, so append
    last->next = compile;
  }
  else
  {
    // first command, set as first
    commands->compile = compile;
  }

  // add the payload
  compile->command = strdup(compile_cmds[i]);
  compile->next = NULL;

  // keep track of last to easy append
  last = compile;
}

...

你可能已经注意到你的函数中有重复的代码,所以一个想法就是一次为一个编译或测试创建一个函数read_commands,然后再调用它两次。

e.g。

 read_commands(Command** cmd, const char** cmds);
 ...
 Commands c = {NULL,NULL};
 read_commands(&c.compile, compileCmds);
 read_commands(&c.test, testCmds);

extra *是为了能够改变指针指向

的内容
 read_commands(Command** pc, const char* cmds)
 {
    ... 
    *pc = malloc(sizeof(Command));
    ...
 }