How to handle argv array assignments?

I found two ways to pass command line arguments to an array of characters:

int main (int argc, char **argv)
{
  const char *s1 = argv[0];
  char s2[256];
  strcpy(s2, argv[0]);

  printf("s1: %s\ns2: %s\n\n", s1, s2);
}

Compiled with the IBM xlc compiler on an AIX system. Returns

[MyPrompt]> ./a.out

s1: ./ a.out

s2: ./ a.out

Which implementation (s1 or s2) is correct? s1 is good because argv [0] can be any length. s2 requires a length of argv [0] of 256 characters.

I do not understand how / why s1 should work. I think the right side of s1 should be required at compile time, but I think that it was generated at runtime.

+3
source share
6 answers

s1 , argv [0] . ( ), . - .

, .

+3

, s1 .

, . strnlen() strncpy(), .

+3

, s1 , , .

, , . :

void f() {
   int x = 1;
   ...
}

x 1 , .

+1

s2 .

, argv [0]. ( ) argv [0] , ps , .

+1

- , s1 .

- , , s2, s2 ., , , . , filename.jpg filename.gif , , .jpg .gif

0

I would go with s1, especially for argv [n], where n> 0. Things like s2 open you up for classic buffer overflow attacks. Basically, a user can format an argument longer than 256 characters and overwrite the information on the stack so that they can run whatever code they need.

0
source

Source: https://habr.com/ru/post/1714089/


All Articles