adm
adm

Reputation: 179

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.

Upvotes: 7

Views: 1758

Answers (1)

P.P
P.P

Reputation: 121407

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.

Upvotes: 10

Related Questions