问题
I am taking command line argument which I am copying to my character pointer. but its giving me an error.
int main(int argc, char *argv[])
{
char *cmdarg;
if(argc>1)
strcpy(cmdarg, argv[1]);
else
cmdarg = NULL;
return 0;
}
This gives me
Segmentation fault (core dumped)
回答1:
You did not allocate memory where you are going to copy the argument pointed to by the expression argv[1]
.
Try the following
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *cmdarg = NULL;
if( argc > 1 )
{
cmdarg = malloc( strlen( argv[1] ) + 1 );
if ( cmdarg != NULL ) strcpy( cmdarg, argv[1] );
}
// ... Some other code
free( cmdarg );
return 0;
}
If you want just to store the value of the pointer argv[1]
then write
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *cmdarg = NULL;
if( argc > 1 )
{
cmdarg = argv[1];
}
// ... Some other code
return 0;
}
回答2:
cmdarg is a Uninitialized pointer by declaration. We have to allocate dynamic memory for cmdarg to point to. Below is a sample code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *cmdarg;
cmdarg = malloc( 5 * sizeof(char));
if(argc>1)
{
strcpy(cmdarg, argv[1]);
printf("%s\n", cmdarg);
}
else
cmdarg = NULL;
free(cmdarg);
return 0;
}
Output while running with argument ./a.out yes
is yes
.
Note: Size allocated should not be lesser while using strcpy(). Make sure to use strncpy()
来源:https://stackoverflow.com/questions/60237281/cannot-copy-command-line-argument-to-character-pointer-in-c