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

时间:2013-03-20 12:17:57

标签: 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位窗口的cygwin中运行它。

修改

这是格式

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

2 个答案:

答案 0 :(得分:2)

更改此

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成员。

答案 1 :(得分:0)

您没有为formatvcs分配任何存储空间。它们是只是指针。如果你想让它们指向一个字符串,你需要空间来存储字符串数据本身以及终结符('\ 0')的空间。处理它的一种方法是在选项上调用strlen()来获取它的长度,然后使用该信息,这样你就可以使用malloc()来分配足够大的空间来容纳完整的C字符串,然后使用struct中的指针指向该内存块。