我的函数被传递了一个结构,其中包含一个以 NULL 结尾的指针数组,这些指针指向组成带有参数的命令的单词。
我正在对参数列表执行全局匹配,以将它们扩展为完整的文件列表,然后我想用新的扩展参数数组替换传递的参数数组。
globbing 工作正常,即 g.gl_pathv 填充了预期文件的列表。但是,我无法将此数组复制到给定的结构中。
#include <glob.h>
struct command {
char **argv;
// other fields...
}
void myFunction( struct command * cmd )
{
char **p = cmd->argv;
char* program = *p++; // save the program name (e.g 'ls', and increment to the first argument
glob_t g;
memset(&g, 0, sizeof(g));
g.gl_offs = 1;
int res = glob(*p++, GLOB_DOOFFS, NULL, &g);
glob_handle_res(res);
while (*p)
{
res = glob(*p, GLOB_DOOFFS | GLOB_APPEND, NULL, &g);
glob_handle_res(res);
}
if( g.gl_pathc <= 0 )
{
globfree(&g);
}
cmd->argv = malloc((g.gl_pathc + g.gl_offs) * sizeof *cmd->argv);
if (cmd->argv == NULL) { sys_fatal_error("pattern_expand: malloc failed\n");}
// copy over the arguments
size_t i = g.gl_offs;
for (; i < g.gl_pathc + g.gl_offs; ++i)
cmd->argv[i] = strdup(g.gl_pathv[i]);
// insert the original program name
cmd->argv[0] = strdup(program);
** cmd->argv[g.gl_pathc + g.gl_offs] = 0; **
globfree(&g);
}
void
command_free(struct esh_command * cmd)
{
char ** p = cmd->argv;
while (*p) {
free(*p++); // Segfaults here, was it already freed?
}
free(cmd->argv);
free(cmd);
}
编辑 1:另外,我意识到我需要将程序作为 cmd->argv[0] 粘贴到那里
编辑 2:添加对 calloc 的调用
编辑 3:使用 Alok
编辑 4 的提示编辑内存管理:来自 alok
编辑 5 的更多提示:几乎工作..释放命令结构时应用程序段错误
最后:好像我错过了终止 NULL,所以添加以下行:
cmd->argv[g.gl_pathc + g.gl_offs] = 0;
似乎使它工作。