Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3277726
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T19:24:04+00:00 2026-05-17T19:24:04+00:00

Ok basically I’m writing a program that takes in two directories and processes them

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T19:24:05+00:00Added an answer on May 17, 2026 at 7:24 pm

    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;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically I'm trying to accomplish the same thing that mailto:bgates@microsoft.com does in Internet Explorer
Basically I’ve heard that certain conditions will cause .NET to blow past the finally
Basically I need to open a login window in a popup, so that it
Basically what I want to do it this: a pdb file contains a location
Basically, something better than this: <input type=file name=myfile size=50> First of all, the browse
Basically I have some code to check a specific directory to see if an
Basically I'm going to go a bit broad here and ask a few questions
Basically, I would like a brief explanation of how I can access a SQL
Basically I am trying to restart a service from a php web page. Here
Basically, I'm trying to tap into the Soap pipeline in .NET 2.0 - I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.