How To: Security-Oriented C Tutorial 0x11 - Command Line Arguments

Security-Oriented C Tutorial 0x11 - Command Line Arguments

Security-Oriented C Tutorial 0x11 - Command Line Arguments

In many programs on Linux, you'll come across programs which allow you to specify additional arguments instead of just simply running the program by itself. If you've used the Kali distribution, I'm more than certain you'll have come across these with the command line tools, else if you have been following these tutorials, we have already come across three tools which also use the same technique, i.e. gcc, gdb and wc. How do we do this with C? Let's find out.


Two arguments which can exist for main are called argc and argv which are of types int and char (*)[] (pointer to an array) respectively. argc is an abbreviation of argument count and argv is argument vector. argc contains the number of arguments passed into main and argv contains an array of the arguments as strings. argc by default is always 1 because the executable is always the first argument which also means it is the first string of argv (argv[0]).

Example Code

To illustrate the argv array, let's type up some code to see the results.

We now have a new way to define main with int argc, char *argv[]. The program loops until it has passed through all of main's command line arguments and prints out each corresponding argv string.

Note: Escapes (\) are required to tell C that the double quotes are to be taken as literal characters. The \b character is the backspace key equivalent and is used here for visual formatting.

Compiling and Running

Wonderful! In case you were wondering, this would be how the char *[] array would be initialized in code, e.g. char *strArray[] = {"Some", "String here", "Null-Byte", "42"};

Now that we can capture the arguments, we can do some pretty neat things like checking for the appropriate number of arguments with argc and printing usage messages.

Example Code

Compiling and Running

We try different attempts at running the program and it only works correctly if we have two arguments or more. To be able to register strings with spaces, you must type the string within a pair of double quotation marks.


With these new parameters, we are able to give input to the program without having to use input functions such as scanf which can be vulnerable. We can also specify arguments and control how we want the program to function by checking the argc variable. It's a pretty neat trick and we will indeed be using this in later tutorials.



Thanks a lot for your tutorials. You are really helping this community. Merry Christmas.

+1 Kudos

Hey ManWuzi!

It's my pleasure! And a Merry Christmas to you too!


Share Your Thoughts

  • Hot
  • Latest