I'm learning about buffer overflows today and I came across many examples of programs which are vulnerable. The thing which makes me curious is, if there is any reason to work with program's arguments like this:
int main(int argc, char *argv[])
{
char argument_buffer[100];
strcpy(argument_buffer, argv[1]);
if(strcmp(argument_buffer, "testArg") == 0)
{
printf("Hello!\n");
}
// ...
}
Instead of simply:
int main(int argc, char *argv[])
{
if(strcmp(argv[1], "testArg") == 0)
{
printf("Hello!\n");
}
}
Please notice that I know about cons of strcpy
etc. - it's just an example. My question is - is there any true reason for using temporary buffers to store arguments from argv? I assume there isn't any, but therefore I'm curious, why is it present in overflow examples, while in the reality it is never used? Maybe because of pure theory.
Amongst other things, it allows for quick checking that the correct number of arguments has been passed. 2 ... argc shall be the number of arguments passed to the program from the environment in which the program is run. ....
The second parameter, argv (argument vector), is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
argv[1] is a pointer to a string. You can print the string it points to using printf("%s\n", argv[1]); To get an integer from a string you have first to convert it. Use strtol to convert a string to an int .
One possible real-world example: a program that renames *.foo
to *.bar
; you'll need both the original file name and a copy of it with the .foo
part changed to .bar
for the call to rename()
.
IIRC argv and its contents were not guaranteed to be writable and stable on all platforms, in the old times. C89 / C90 / ANSI-C standarized some of the existing practices. Similar for envp[]. Could also be that the routine of copying was inspired by the absence of memory protection on older platforms (such as MS-DOS). Normally (and nowadays) the OS and/or CRT takes care of copying the args form the caller's memory to the process's private memory arena.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With