0

私の目標は、状態を表示するVCSを明示的に指定する追加のパラメーターを使用するようにvcpromptを変更することです。変更の要点は次のとおりです。

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;
4

2 に答える 2

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メンバーにも当てはまります。

于 2013-03-20T12:36:59.093 に答える
0

format割り当てられた、またはvcsポイントするストレージスペースがありません。現状では、それらは単なるポインタです。文字列を指すようにする場合は、文字列データ自体を格納するためのスペースと、ターミネータ('\ 0')用のスペースが必要です。これを処理する1つの方法は、オプションを呼び出しstrlen()てその長さを取得し、その情報を使用malloc()して、完全なC文字列を保持するのに十分な大きさのスペースを割り当て、構造体のポインターがそのメモリブロックを指すようにすることです。 。

于 2013-03-20T12:24:11.870 に答える