红联Linux门户
Linux帮助

memset 和 optarg 的问题

发布时间:2009-02-25 09:36:16来源:红联作者:jiangsu04
#include
#include
#include
#include

int main(int argc, char **argv)
{
int opt;

char *s[] = {"./code", "-a", "hello", "-o", "para" };

if (argc!=5)
{
argc = 5;
argv = s;
}
printf("%d \n", argc);

while((opt = getopt(argc, argv, "o:a:s:")) != EOF) {
switch(opt) {
case 'o':
printf ("o %s\n", optarg);
break;
case 'a':
printf ("a %s\n", optarg);
int len = strlen(optarg);
printf("len is %d\n", len);
printf("optarg is %s\n", optarg);
memset(optarg, 'X', len);
break;
case 's':
printf ("s %s\n", optarg);
break;
default:
break;
}
}

return 0;
}


全部代码如上,生成code.exe 如果从命令行输入 ./code -a dsfds -o para
代码正常,但如果仅仅输入 ./code 引发Segmentation fault (core dumped)

这两种执行方式为何后者出现问题 ? 如何解决 ? 谢谢
文章评论

共有 0 条评论