0
我想爲自定義shell實現globbing
,但是當我嘗試使用該函數時發生段錯誤。如何使用glob函數?
#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代碼,然後我得到一個段錯誤。爲什麼它不起作用?
您是否嘗試過與一些打印功能,一個調試器或類似Valgrind的內存檢查任何調試? – Evert
@ v7d8dpo4你很幸運,因爲代碼中存在一些未定義的行爲。哪個valgrind容易指出。 – Evert
'strcat(gfilename,* p);'很慢。最好在循環之前有'char * tmp = gfilename;',在循環之前有'tmp = stpcpy(tmp,* p);'和'*(tmp ++)='';'。 – v7d8dpo4