LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C: problem with strdup against array (https://www.linuxquestions.org/questions/programming-9/c-problem-with-strdup-against-array-794964/)

schurt 03-12-2010 09:23 AM

C: problem with strdup against array
 
Does anyone see a problem with my code? attempting to do a strdup is failing with a segmentation fault within libc

plugintools.h
Code:

/* Provide function for adding files to be copied/linked
  into report
*/
typedef struct file_list {
  int count;
  char **filepath;
} file_list;

// max path length for any file/dir listing
#define MAXPATHLEN 1024
file_list *
add_copy_spec(const char *path);

plugintools.c
Code:

/* add file specification (dir, file, shell glob)
 */
file_list *
add_copy_spec(const char *path)
{
    int err, i;
    char *abspath[MAXPATHLEN];
    glob_t globbuf;

    struct file_list *fl = (file_list *)malloc(sizeof(file_list));
   
    err = glob(path, GLOB_DOOFFS | GLOB_APPEND, NULL, &globbuf);
    if (err) {
        fl->count = 0;
        fl->filepath = NULL;
        return fl;
    }
   
    fl->count = globbuf.gl_pathc;
    fl->filepath = (char **)malloc(sizeof(char *) * fl->count);
    // loop through our file list, append to struct array
    printf("\nfilepath loop\n");
    for (i = 0; i < globbuf.gl_pathc; i++) {
        printf("%s\n", globbuf.gl_pathv[i]);
        fl->filepath[i] = strdup(globbuf.gl_pathv[i]);

/*
        if((realpath(globbuf.gl_pathv[i], abspath)) != NULL) {
            //fl->filepath[i] = strdup(globbuf.gl_pathv[i]);
          } else {
            continue;
        }
*/
    }
    globfree(&globbuf);
    return fl;
}


estabroo 03-12-2010 06:37 PM

Your glob flags GLOB_DOOFFS and GLOB_APPEND seem to be used incorrectly, DOOFFS shouldn't be used with an uninitalized glob_t since it uses the glob_t gl_offs information. GLOB_APPEND shouldn't be used in the first call to glob and since your glob_t var goes away every time you call add_copy_spec you probably shouldn't have that flag in there at all.

Either one of those used that way could make your return state undefined for your globbuf info


All times are GMT -5. The time now is 08:14 PM.