有史以来最奇怪的分段错误
好吧,基本上我正在编写一个程序,它接受两个目录并根据提供的选项处理它们。问题是,当我没有看到问题时,它有时会给我分段错误。导致问题的代码如下:
编辑:更新代码以包含我的整个源文件
#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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
strcpy()
将argv[optind]
复制到您刚刚分配的*tempPaths
空间中。事实上,您正在破坏(泄漏)分配的内存,然后谁知道还会出现什么问题。
另外,为什么你需要复印你的论点?如果您不修改它们,则无需复制它们。
这假设您确实需要复制您的论点。如果您不需要修改命令行参数,您可以简单地使用:
当我编辑以删除不再需要的内容时,那里的代码刚刚消失了...
甚至可以简单地设置:
这消除了循环和临时变量一起!
回答评论里的问题
您的原始代码是:
第一条语句将内存分配给 *tempPaths;第二个然后用指针 argv[optind] 覆盖(唯一引用)该指针,从而确保您无法释放分配的内存,并确保您没有使用它。此外,如果您随后尝试释放 ... 指向的内存,那么到此阶段它将是
paths
而不是tempPaths
... 那么您正在尝试从未分配的空闲内存,这也是一件坏事™。您的代码正在复制传递给程序的参数(目录名称);修改后的解决方案使用
strdup()
(或者大致是strdup()
的主体)在argv[optind]
中复制数据>。但是,如果您对数据所做的只是读取数据而不更改它,则可以简单地复制指针,而不是复制数据。 (即使您要修改参数,如果您小心的话,您仍然可以使用原始数据 - 但制作副本会更安全。)不;它会给你一个指向以空结尾的字符串指针列表的指针,你可以单步执行:
裸露的最小工作代码
正如评论中所指出的,扩展崩溃代码的基本问题(除了我们不这样做的事实之外)没有标题)的原因是
paths
变量未初始化为指向任何内容。难怪代码会崩溃。基于修改后的示例 - 删除了选项处理:
并且此版本进行内存分配:
You need to use
strcpy()
to copyargv[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.
This assumes you do need to copy your arguments. If you don't need to modify the command line arguments, you can simply use:
The code there just vanished as I was editing to remove what was no longer necessary...
It might even be possible to simply set:
This does away with the loop and temporary variables altogether!
Answering questions in comment
Your original code is:
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 thantempPaths
by this stage ... then you are attempting to free memory that was never allocated, which is also a Bad Thing™.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 ofstrdup()
) makes a copy of the data inargv[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.)No; it would give you a pointer to a null-terminated list of pointers to strings, which you could step through:
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:
And this version does memory allocation:
您已发现段错误发生在以下行之一:
argv
中的条目数极不可能少于argc
条目,因此我们推断问题出在分配上到*tempPaths
,因此tempPaths
不能是有效的指针。由于您没有显示
paths
是如何初始化的,因此不可能进行更深入的挖掘。paths
中的成员很可能少于argc
,因此您的tempPaths++
会导致您越过最后一个条目。You have identified that the segfault is occurring on one of these lines:
It's highly unlikely that there are fewer than
argc
entries inargv
, so we deduce that the problem is the allocation to*tempPaths
, sotempPaths
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 thanargc
members inpaths
, so yourtempPaths++
is causing you to move past the last entry.