c - 分配给作为结构成员的指针会导致段错误

标签 c segmentation-fault c99

我的目标是修改vcprompt以这样的方式,它需要额外的参数来明确指定哪个 VCS 显示状态。以下是更改的要点:

typedef struct {
    int debug;
    char *format;                       /* e.g. "[%b%u%m]" */
    int show_branch;                    /* show current branch? */
    int show_revision;                  /* show current revision? */
    int show_patch;                     /* show patch name? */
    int show_unknown;                   /* show ? if unknown files? */
    int show_modified;                  /* show + if local changes? */
    unsigned int timeout;               /* timeout in milliseconds */
    char *vcs;                          /* e.g. "git", "hg" */
} options_t;

...

options_t options = {
    .debug         = 0,
    .format        = format,
    .show_branch   = 0,
    .show_revision = 0,
    .show_unknown  = 0,
    .show_modified = 0,
    .vcs           = NULL
};

...

int opt;
while ((opt = getopt(argc, argv, "hf:dt:v:")) != -1) {
    switch (opt) {
        case 'f':
            options->format = optarg;
            break;
        case 'd':
            options->debug = 1;
            break;
        case 't':
            options->timeout = strtol(optarg, NULL, 10);
            break;
        case 'v':
            printf("%s %s", options->vcs, optarg);
            //options->vcs = optarg;
            break;
    ...
}

当我像 ./vcprompt -v foo 那样调用程序时,printf 在输出中添加以下内容:(null) git。如果我取消注释 printf 下面的赋值,则会出现段错误。

这可能是什么原因造成的?在我看来,我使用 vcs 所做的事情与使用 format 所做的事情是相同的。我在 64 位 Windows 上的 cygwin 中运行它。

编辑

这是格式的定义

#define DEFAULT_FORMAT "[%n:%b] "
...
char *format = getenv("VCPROMPT_FORMAT");
if (format == NULL)
    format = DEFAULT_FORMAT;

最佳答案

改变这个

while ((opt = getopt(argc, argv, "hf:dt:v:")) != -1) {
    switch (opt) {
        case 'f':
            options->format = optarg;
            break;
...

到此

while ((opt = getopt(argc, argv, "hf:dt:v:")) != -1) {
    switch (opt) {
        case 'f':
            options->format = strdup(optarg);
            break;

...

这样就创建了选项的副本并在堆上分配 - 对于 vcs 成员也是如此。

关于c - 分配给作为结构成员的指针会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15523328/

相关文章:

c - 如何在 C 中返回匿名结构?

c - C 中有哪些 XML API?

c++ - 释放指针时出现段错误

c - 结构中 restrict 关键字的行为

c - 为什么有些 C 标准头文件以 'std' 开头,而有些则不是?

c - 奇怪的段错误(数组和指针之间的区别?)

c - 如何在 C 中将 ENUM 作为函数参数传递

c - 关于这个将十进制数打印成二进制的循环的建议

c - 设置 FLT_EVAL_METHOD 不起作用

C LIBCHAMPLAIN 段错误?