views:

229

answers:

2

Ok basically I'm writing a program that takes in two directories and processes them based on what options are supplied. Thing is it's giving me segmentation errors at times when I don't see a problem. The code that is causing the problem is the following:

EDIT: Update the code to include my entire source file

#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>

#define OPTLIST "am:npruv"
#define DEFAULT_MOD_TIMES 1

typedef struct
{
    /* Boolean toggle to indicate whether hidden files should be
       processed or not */
    bool processHiddens;
    /* Integer number of seconds such that files with modification
       times that differ by less than this value are considered the
       same */
    int timeResolution;
    /* Boolean toggle to indicate whether the actual synchronisation
       (file creation and overwriting) should be performed or not */
    bool performSync;
    /* Boolean toggle to indicate whether subdirectories should be
       recursively processed or not */
    bool recursive;
    /* Boolean toggle to indicate whether to print the combined
       directory structure or not */
    bool print;
    /* Boolean toggle to indicate whether modification times and
       permissions should be updated or not */
    bool updateStatus;
    /* Boolean toggle to indicate whether verbose output should be
       printed or not */
    bool verbose;
    /* The name of the executable */
    char *programname;
} OPTIONS;

int main(int argc, char *argv[])
{
    static OPTIONS options;
    //static TOPLEVELS tls;
    int opt;
    char **paths;

    /*
     * Initialise default without options input.
     * Done the long way to be more verbose.
     */
    opterr = 0;
    options.processHiddens = false;
    options.timeResolution = DEFAULT_MOD_TIMES;
    options.performSync = true;
    options.recursive = false;
    options.print = false;
    options.updateStatus = true;
    options.verbose = false;
    options.programname = malloc(BUFSIZ);
    options.programname = argv[0];

    /*
     * Processing options.
     */
    while ((opt = getopt(argc, argv, OPTLIST)) != -1)
    {
        switch (opt)
        {
            case 'a':
                options.processHiddens = !(options.processHiddens);
                break;
            case 'm':
                options.timeResolution = atoi(optarg);
                break;
            case 'n':
                options.performSync = !(options.performSync);
                break;
            case 'p':
                options.print = !(options.print);
                break;
            case 'r':
                options.recursive = !(options.recursive);
                break;
            case 'u':
                options.updateStatus = !(options.updateStatus);
                break;
            case 'v':
                options.verbose = !(options.verbose);
                break;
            default:
                argc = -1;
        }
    }

    /*
     * Processing the paths array for top level directory.
     */
    char **tempPaths = paths;
    while (optind < argc)
    {
        *tempPaths++ = argv[optind++];
    }

    if (argc -optind + 1 < 3)
    {
        fprintf(stderr, "Usage: %s [-amnpruv] dir1 dir2 [dirn ... ]\n", options.programname);
        exit(EXIT_FAILURE);
    }
    else
    {
        //processTopLevelDirectories(tls, paths, nDirs, options);
        exit(EXIT_SUCCESS);
    }

    return 0;
}

I have a bash script that when runs does the following:

#!/bin/bash
clear
echo Running testing script
echo Removing old TestDirectory
rm -r ./TD
echo Creating new copy of TestDirectory
cp -r ./TestDirectory ./TD
echo Building program
make clean
make
echo Running mysync
./mysync ./TD/Dir1 ./TD/Dir2
echo Finished running testing script

However if I were to try to run the program manually using the EXACT same command:

./mysync ./TD/Dir1 ./TD/Dir2

I get a segmentation fault between test1 and test2. But if I were to append a / to just any one of the directories, or both, then it works again. Any ideas guys?

EDIT: source_collection.h is basically all of the supporting source codes, so far they have not been implemented yet so they shouldn't cause any problems. OPTIONS is a supplied structure, thus it should be error-free. The current source is still work in progress so there's still some code missing as well as having some codes commented out. Basically at the end of the day the program aims to take in n directories with options and sync the directories.

+8  A: 

You need to use strcpy() to copy argv[optind] into your *tempPaths space that you've just allocated.

As it is, you are clobbering (leaking) your allocated memory and then who knows what else goes wrong.

Also, why do you need to make a copy of your arguments? If you don't modify them, you don't need to copy them.


char **tempPaths = paths;
while (optind < argc)
{
    printf("test1\n");
    // Or use strdup(), but strdup() is POSIX, not Standard C
    // This wastes less space on short names and works correctly on long names.
    *tempPaths = malloc(strlen(argv[optind])+1);
    // Error check omitted!
    strcpy(*tempPaths, argv[optind]);
    printf("test2\n");
    printf("%s\n", *tempPaths);
    tempPaths++;
    optind++;
}

This assumes you do need to copy your arguments. If you don't need to modify the command line arguments, you can simply use:

char **tempPaths = paths;
while (optind < argc)
    *tempPaths++ = argv[optind++];

The code there just vanished as I was editing to remove what was no longer necessary...

It might even be possible to simply set:

char **paths = &argv[optind];

This does away with the loop and temporary variables altogether!


Answering questions in comment

[W]hat do you mean when you say that my allocated memory is leaking?

Your original code is:

*tempPaths = malloc(BUFSIZ);
*tempPaths = argv[optind];

The first statement allocates memory to *tempPaths; the second then overwrites (the only reference to) that pointer with the pointer argv[optind], thus ensuring that you cannot release the allocated memory, and also ensuring that you are not using it. Further, if you subsequently attempt to free the memory pointed to by ... well, it would be paths rather than tempPaths by this stage ... then you are attempting to free memory that was never allocated, which is also a Bad Thing™.

Also I don't particularly get what you mean by "make a copy of your arguments". Are you referring to the two directories used for the command line or for something else?

Your code is making a copy of the arguments (directory names) passed to the program; the revised solution using strdup() (or what is roughly the body of strdup()) makes a copy of the data in argv[optind]. However, if all you are going to do with the data is read it without changing it, you can simply copy the pointer, rather than making a copy of the data. (Even if you were going to modify the argument, if you were careful, you could still use the original data - but it is safer to make a copy then.)

Finally wouldn't char **paths = &argv[optind]; just give me a single directory and that's it?

No; it would give you a pointer to a null-terminated list of pointers to strings, which you could step through:

for (i = 0; paths[i] != 0; i++)
    printf("name[%d] = %s\n", i, paths[i]);

Bare minimal working code

As noted in a comment, the basic problem with the expanded crashing code (apart from the fact that we don't have the header) is that the paths variable is not initialized to point to anything. It is no wonder that the code then crashes.

Based on the amended example - with the options processing stripped out:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char **paths;

    optind = 1;
    paths = &argv[optind];

    if (argc - optind + 1 < 3)
    {
        fprintf(stderr, "Usage: %s dir1 dir2 [dirn ... ]\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    else
    {
        char **tmp = paths;
        while (*tmp != 0)
            printf("<<%s>>\n", *tmp++);
    }

    return 0;
}

And this version does memory allocation:

#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    optind = 1;

    if (argc - optind + 1 < 3)
    {
        fprintf(stderr, "Usage: %s dir1 dir2 [dirn ... ]\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    else
    {
        int npaths = argc - optind;
        char **paths = malloc(npaths * sizeof(*paths));
        // Check allocation!
        char **tmp = paths;
        int i;
        printf("n = %d\n", npaths);
        for (i = optind; i < argc; i++)
        {
            *tmp = malloc(strlen(argv[i])+1);
            // Check allocation!
            strcpy(*tmp, argv[i]);
            tmp++;
        }
        for (i = 0; i < npaths; i++)
            printf("<<%s>>\n", paths[i]);
    }

    return 0;
}
Jonathan Leffler
Sorry but what do you mean when you say that my allocated memory is leaking? Also I don't particularly get what you mean by "make a copy of your arguments". Are you referring to the two directories used for the command line or for something else? Finally wouldn't `char **paths = ` just give me a single directory and that's it?
jon2512chua
Also even after changing my code to `*tempPaths++ = argv[optind++];` my original problem still persists.
jon2512chua
@jon2512chua: there were sufficient problems in the code you show that the residual issues could be anywhere. If you can provide a minimal crashing program (a minimal program that compiles but illustrates your crash), then we can maybe debug it for you. But we don't know how `paths` is declared, for example; we also don't know how you are processing arguments generally - the variable `optind` suggests you are using `getopt()` (which is good!) but isn't conclusive.
Jonathan Leffler
I've updated my code and provided some more information in the post above. :)
jon2512chua
Just to double check, `*tmp != 0` is equivalent to `*tmp != NULL` right?
jon2512chua
@jon2512chua: correct - `*tmp != 0` is equivalent to `*tmp != NULL` because NULL 'expands to an implementation-defined null pointer constant' (C99 §7.17) and an 'integer constant expression with the value 0, or such an expression cast to typevoid *, is called a null pointer constant' (C99 §6.3.2.3).
Jonathan Leffler
Ok got it! Thanks for all your help and patience.
jon2512chua
A: 

You have identified that the segfault is occurring on one of these lines:

*tempPaths = malloc(BUFSIZ);
*tempPaths = argv[optind];

It's highly unlikely that there are fewer than argc entries in argv, so we deduce that the problem is the allocation to *tempPaths, so tempPaths cannot be a valid pointer.

Since you don't show how paths is initialised, it's impossible to dig any deeper. Most likely there are fewer than argc members in paths, so your tempPaths++ is causing you to move past the last entry.

Porculus
I've updated my original post with the complete code as well as additional info. Though I don't think `tempPaths++` is moving past the last entry as my test script doesn't give a segmentation fault, nor does appending a `/` to the end of either one or both of the directory arguments.
jon2512chua