我的目标是修改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/