简体   繁体   中英

Copying string from argv to char array in C

I have following code which copy argument string to char array.

char *str = malloc(strlen(argv[1]) + 1);
strcpy(str, argv[1]);

printf("%s\n", str);

Why when I pass following argument:

$6$4MfvmFOaDUaa5bfr$cvtrefr

I get:

MfvmFOaDUaa5bfr

Instead of whole string. Somewhere I lose first number. I tried various of method and every one works the same or doesn't work either.

My key is get only salt(in this case) 4MfvmFOaDUaa5bfr or $6$4MfvmFOaDUaa5bfr without third $ character. I try to also get method to copy string while I meet the third $ and then stop copying.

Because in the string $6$4MfvmFOaDUaa5bfr$cvtrefr , the $6 , $4 and $cvtrefr are expanded by the shell for positional arguments and variables and they are all empty.

Pass the argument with single quotes:

./a.out '$6$4MfvmFOaDUaa5bfr$cvtrefr'

which will prevent the shell expansion.

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