我正在C中重构一个旧的代码库。我有一个结构:
struct example_opt_t
{
const char *name;
const char *value;
};
我想初始化我的选项(名称、值(,以便将其传递给init
函数。
这是init()
声明:
struct lh_ctx_t *init( const struct example_clb_t *callbacks, void *user_data, const struct example_opt_t *options ) {
这是我尝试初始化options
:
const struct example_opt_t my_options[2] = {
(struct example_opt_t){
"option1_name",
"option1_value",
},
(struct example_opt_t){"option2_name",
"option2_value"},
};
但我有点毛病。我在这里做错了什么?
[更新]:
init
在某个时刻调用以下函数:
if ( example_strcasecmp( option->name, name ) ) return false;
其主体为:
int example_strcasecmp( const char *s1, const char *s2 ) {
int diff;
if ( s1 == NULL || s2 == NULL ) return 0;
/* I'm getting a segfault at the line below*/
do { diff = example_lowercase(s1++) - example_lowercase(s2++); }
while ( diff == 0 && s1[-1] != ' ' );
return diff;
}
example_lowercase
为:
int example_lowercase( const char *s ) {
return tolower( *(const unsigned char *)s );
}
奇怪的是,我仍然得到一个segfault,但现在我看不到它生成的确切行,因为gdb输出如下:
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x000055aace859039 in ?? ()
(gdb) bt
#0 0x000055aace859039 in ?? ()
#1 0x000055aacf4b6268 in ?? ()
#2 0x000055aace85671a in ?? ()
#3 0x00007ffe39cd0e34 in ?? ()
#4 0x000055aacf4b6268 in ?? ()
#5 0x00007ffe39cd0f40 in ?? ()
#6 0x00007ffe39cd0f20 in ?? ()
#7 0x00007ffe39cd0e34 in ?? ()
#8 0x000055aace857f6f in ?? ()
#9 0x000055aacf4b6268 in ?? ()
#10 0x5d4ca731752bb200 in ?? ()
#11 0x00007ffe39cd0f20 in ?? ()
#12 0x000055aacf4b6268 in ?? ()
#13 0x0000000000000000 in ?? ()
当strlen(s1(>strlen((s2(运行超过s2的末尾时,将进入未映射的内存。
更改此-
while ( diff == 0 && s1[-1] != ' ' );
到此-
while ( diff == 0 && s1[-1] != ' ' && s2[-1] != ' ' );
并确认这是否解决了您的问题。