简体   繁体   中英

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 . 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).

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. 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:

 $ ./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)
 $ 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM