Search code examples
cglob

How to use the glob function?


I want to implement globbing for a custom shell but when I try to use the function a get a segfault.

#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;
}

If I try and use the abose code then I get a segfault. Why doesn't it work?


Solution

  • The problem is because length is not initialized before you accumulate lengths of paths into it.

    length = 0; <-- should initialize length here
    for (p = glob_results.gl_pathv, cnt = glob_results.gl_pathc; cnt; p++, cnt--)
        length += strlen(*p) + 1;
    

    Also, don't cast return value of calloc, and sizeof(char) is defined to be 1 in the standard. So it's better just do:

    gfilename = calloc(length, 1);
    

    or

    gfilename = malloc(length);