我想为自定义shell实现globbing
但是当我尝试使用该函数时,获取段错误。
#include <stdlib.h>
#include <string.h>
#include <glob.h>
/* Convert a wildcard pattern into a list of blank-separated
filenames which match the wildcard. */
char * glob_pattern(char *wildcard)
{
char *gfilename;
size_t cnt, length;
glob_t glob_results;
char **p;
glob(wildcard, GLOB_NOCHECK, 0, &glob_results);
/* How much space do we need? */
for (p = glob_results.gl_pathv, cnt = glob_results.gl_pathc;
cnt; p++, cnt--)
length += strlen(*p) + 1;
/* Allocate the space and generate the list. */
gfilename = (char *) calloc(length, sizeof(char));
for (p = glob_results.gl_pathv, cnt = glob_results.gl_pathc;
cnt; p++, cnt--)
{
strcat(gfilename, *p);
if (cnt > 1)
strcat(gfilename, " ");
}
globfree(&glob_results);
return gfilename;
}
如果我尝试使用abose代码,那么我会遇到段错误。为什么不起作用?
答案 0 :(得分:1)
问题是因为length
在累积路径长度之前未初始化。
length = 0; <-- should initialize length here
for (p = glob_results.gl_pathv, cnt = glob_results.gl_pathc; cnt; p++, cnt--)
length += strlen(*p) + 1;
此外,不要转换calloc
的返回值,并且sizeof(char)
在标准中定义为1。所以最好这样做:
gfilename = calloc(length, 1);
或
gfilename = malloc(length);