[英]Error in copying argv to char array
I am trying to copy argv to char array, been through some solutions online but ending up in getting Segmentation Fault . 我正在尝试通过在线一些解决方案将argv复制到char数组, 但最终导致得到Segmentation Fault 。 Following is the code i used:
以下是我使用的代码:
void main (int argc,const char *argv[])
{
char *arr;
arr = (char *) malloc(strlen(argv[1])+1);
strcpy(arr,argv[1]);
}
Please help to identify what I am doing wrong. 请帮助确定我在做什么错。
It seems that argv[1] is equal to NULL or even does not exist (The C Standard allows that argc may be equal to 0). 似乎argv [1]等于NULL甚至不存在(C标准允许argc可以等于0)。
Add the following check 添加以下检查
char *arr;
if ( argc > 1 )
{
arr = (char *) malloc(strlen(argv[1])+1);
strcpy(arr,argv[1]);
}
else
{
// print some error message
}
Please help to identify what I am doing wrong.
请帮助确定我在做什么错。
All right then sir. 好的,先生。 You are asking for argv[1], but you are not sure whether it exists.
您正在询问argv [1],但不确定是否存在。 accessing an array outside its bounds has undefined behavior.
访问其边界之外的数组具有未定义的行为。 You should always check if number of parameters is what you expect to avoid undefined behavior:
您应该始终检查参数数量是否是您期望的值,以避免未定义的行为:
if ( argc < 2 )
{
// error, cannot copy argv[1] because it doesn't exist. Explain this to user
}
// now OK..., also we postponed allocation of arr pointer
char *arr = malloc( strlen( argv[1]) + 1);
//^^^^
// no need to cast return value of malloc in C
strcpy( arr, argv[1]);
When using command line input, we should deal with number of arguments. 当使用命令行输入时,我们应该处理参数数量。
You can try something like this.. 您可以尝试这样的事情。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main (int argc, const char *argv[])
{
if(argc==2)//change condition based on your requirements
{
char *arr;
arr = (char *) malloc(strlen(argv[1])+1);
strcpy(arr,argv[1]);
printf("string is %s\n",arr);
}
else
{
printf("check your command line input (only 2 parameters)\n");
}
}
OUTPUT: OUTPUT:
$ ./a.out
check your command line input (only 2 parameters)
$ ./a.out hello
string is hello
$ ./a.out hi hello
check your command line input (only 2 parameters)
$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.