有史以来最奇怪的分段错误

发布于 2024-09-29 14:19:18 字数 3973 浏览 3 评论 0原文

好吧,基本上我正在编写一个程序,它接受两个目录并根据提供的选项处理它们。问题是,当我没有看到问题时,它有时会给我分段错误。导致问题的代码如下:

编辑:更新代码以包含我的整个源文件

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

我有一个 bash 脚本,运行时执行以下操作:

#!/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

但是,如果我尝试使用完全相同的命令手动运行程序:

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

我在 test1 和 test2 之间遇到分段错误。但是,如果我将 / 附加到任意一个目录或两个目录,那么它会再次起作用。大家有什么想法吗?

编辑:source_collection.h 基本上是所有支持源代码,到目前为止它们还没有实现,所以它们不应该引起任何问题。 OPTIONS 是一个提供的结构,因此它应该是无错误的。当前源代码仍在进行中,因此仍然缺少一些代码以及注释掉一些代码。基本上,在一天结束时,程序的目标是使用选项接收 n 个目录并同步目录。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哆兒滾 2024-10-06 14:19:18

您需要使用 strcpy()argv[optind] 复制到您刚刚分配的 *tempPaths 空间中。

事实上,您正在破坏(泄漏)分配的内存,然后谁知道还会出现什么问题。

另外,为什么你需要复印你的论点?如果您不修改它们,则无需复制它们。


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

这假设您确实需要复制您的论点。如果您不需要修改命令行参数,您可以简单地使用:

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

当我编辑以删除不再需要的内容时,那里的代码刚刚消失了...

甚至可以简单地设置:

char **paths = &argv[optind];

这消除了循环和临时变量一起!


回答评论里的问题

[W]当您说我分配的内存正在泄漏时,您的意思是什么?

您的原始代码是:

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

第一条语句将内存分配给 *tempPaths;第二个然后用指针 argv[optind] 覆盖(唯一引用)该指针,从而确保您无法释放分配的内存,并确保您没有使用它。此外,如果您随后尝试释放 ... 指向的内存,那么到此阶段它将是 paths 而不是 tempPaths ... 那么您正在尝试从未分配的空闲内存,这也是一件坏事™。

另外,我不太明白你所说的“复制你的论点”是什么意思。您指的是用于命令行还是其他用途的两个目录?

您的代码正在复制传递给程序的参数(目录名称);修改后的解决方案使用 strdup()(或者大致是 strdup() 的主体)在 argv[optind] 中复制数据>。但是,如果您对数据所做的只是读取数据而不更改它,则可以简单地复制指针,而不是复制数据。 (即使您要修改参数,如果您小心的话,您仍然可以使用原始数据 - 但制作副本会更安全。)

最后不会 char **paths = &argv[optind];只要给我一个目录就可以了?

不;它会给你一个指向以空结尾的字符串指针列表的指针,你可以单步执行:

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

裸露的最小工作代码

正如评论中所指出的,扩展崩溃代码的基本问题(除了我们不这样做的事实之外)没有标题)的原因是 paths 变量未初始化为指向任何内容。难怪代码会崩溃。

基于修改后的示例 - 删除了选项处理:

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

并且此版本进行内存分配:

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

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;
}
勿忘初心 2024-10-06 14:19:18

您已发现段错误发生在以下行之一:

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

argv 中的条目数极不可能少于 argc 条目,因此我们推断问题出在分配上到 *tempPaths,因此 tempPaths 不能是有效的指针。

由于您没有显示 paths 是如何初始化的,因此不可能进行更深入的挖掘。 paths 中的成员很可能少于 argc,因此您的 tempPaths++ 会导致您越过最后一个条目。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文