2016-04-21 154 views
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代碼,然後我得到一個段錯誤。爲什麼它不起作用?

+1

您是否嘗試過與一些打印功能,一個調試器或類似Valgrind的內存檢查任何調試? – Evert

+1

@ v7d8dpo4你很幸運,因爲代碼中存在一些未定義的行爲。哪個valgrind容易指出。 – Evert

+1

'strcat(gfilename,* p);'很慢。最好在循環之前有'char * tmp = gfilename;',在循環之前有'tmp = stpcpy(tmp,* p);'和'*(tmp ++)='';'。 – v7d8dpo4

回答

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