Reputation: 13
I am trying to copy argv to char array, been through some solutions online but ending up in getting 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.
Upvotes: 0
Views: 3244
Reputation: 1346
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:
$ ./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)
$
Upvotes: 0
Reputation: 311068
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).
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
}
Upvotes: 5
Reputation: 29734
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. 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]);
Upvotes: 0