[英]How to solve segmentation fault in change main function inputs with C code?
I want the following code, which is related to the Sysbench tool ( https://github.com/akopytov/sysbench ), to change from the following code to the next code, but I get an error with just this small change (Segmentation fault (core dumped)).我想要将与 Sysbench 工具 ( https://github.com/akopytov/sysbench ) 相关的以下代码从以下代码更改为下一个代码,但仅通过这个小更改就出现错误 (Segmentation故障(核心转储))。
./sysbench cpu --cpu-max-prime=2000 run
int main(int argc,char *argv[])
{
.
.
.
}
to到
int main(void)
{
char *argv[]= {"./sysbench","cpu","--cpu-max-prime=2000","run", NULL};
int argc = sizeof(argv) / sizeof(char*) - 1;
.
.
.
}
with GDB Debug:使用 GDB 调试:
Program received signal SIGSEGV, Segmentation fault.
0x000000000040aec8 in parse_option (
name=name@entry=0x4768e8 "cpu-max-prime=2000",
ignore_unknown=ignore_unknown@entry=false) at sysbench.c:500
500 *tmp = '\0';
static int parse_option(char *name, bool ignore_unknown)
{
const char *value;
char *tmp;
option_t *opt;
char ctmp = 0;
int rc;
tmp = strchr(name, '=');
printf( "tmp: %s\n", tmp );
if (tmp != NULL)
{
ctmp = *tmp;
*tmp = '\0';
value = tmp + 1;
}
else
{
value = NULL;
}
opt = sb_find_option(name);
if (opt != NULL || ignore_unknown)
rc = set_option(name, value,
opt != NULL ? opt->type : SB_ARG_TYPE_STRING) == NULL;
else
rc = 1;
if (tmp != NULL)
*tmp = ctmp;
return rc;
}
please help me.请帮我。 thanks.谢谢。
In order to emulate argv
from main
the strings pointed to by argv[n]
to must be writable, which is not the case in your code where argv[n]
point to string literals which cannot be written to.为了从main
中模拟argv
, argv[n]
指向的字符串必须是可写的,在您的代码中情况并非如此,其中argv[n]
指向无法写入的字符串文字。
Writing into a string literal is formally undefined behaviour in C, but on modern desktop platforms it typically triggers a seg fault.写入字符串文字在 C 中是正式未定义的行为,但在现代桌面平台上,它通常会触发段错误。
And *tmp = '\0';
并且*tmp = '\0';
is actually writing into a string.实际上是写入一个字符串。
This should do the job, although I'm not entirely sure because I can't check it here easily.这应该可以完成工作,但我不完全确定,因为我无法在此处轻松检查。
int main(void)
{
char arg1[] = "./sysbench";
char arg2[] = "cpu";
char arg3[] = "--cpu-max-prime=2000";
char arg4[] = "run";
char* argv[] = {arg1, arg2, arg3, arg4, NULL};
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.