How are the argc and argv values passed to main() set up? - c++

I want to better understand what's going on under the hood with the command line arguments when a C or C++ program is launched. I know, of course, that argc and argv, when passed to main(), represent the argument count and argument vector, respectively.
What I'm trying to figure out is how the compiler knows to interpret int argc as the number of arguments passed from the command line. If I write a simple function that attempts to mimic main() (e.g. int testfunc(int argc, char* argv[])), and pass in a string, the compiler complains, "Expected 'int' but argument is of type char*" as I would expect. How is this interpreted differently when command line arguments are passed to main()?

In common C implementations, main is not the first routine called when your process starts. Usually, it is some special entry point like _start that is provided by the C library built into your program when you link it. The code at this special entry point examines the command line information that is passed to it (in some way outside of C, particular to the operating system) and constructs an argument list for main. After that and other work, it calls main.

You don't pass argc value on your own (from the command line, for example), it is supplied by your environment (runtime), just like the exact content for argc.[Note below]
To elaborate, C11, chapter §5.1.2.2.1, (indicators mine)
The value of argc shall be nonnegative.
argv[argc] shall be a null pointer.
If the value of argc is greater than zero, the array members argv[0] through
argv[argc-1] inclusive shall contain pointers to strings, which are given
implementation-defined values by the host environment prior to program startup. The
intent is to supply to the program information determined prior to program startup
from elsewhere in the hosted environment. [Note start]If the host environment is not capable of
supplying strings with letters in both uppercase and lowercase, the implementation
shall ensure that the strings are received in lowercase.[Note end]

Related

Define a variable in a shell script that is passed as a command line argument to c++ executable [duplicate]

Everytime I create a project (standard command line utility) with Xcode, my
main function starts out looking like this:
int main(int argc, const char * argv[])
What's all this in the parenthesis? Why use this rather than just
int main()?
main receives the number of arguments and the arguments passed to it when you start the program, so you can access it.
argc contains the number of arguments, argv contains pointers to the arguments.
argv[argc] is always a NULL pointer. The arguments usually include the program name itself.
Typically if you run your program like ./myprogram
argc is 1;
argv[0] is the string "./myprogram"
argv[1] is a NULL pointer
If you run your program like ./myprogram /tmp/somefile
argc is 2;
argv[0] is the string "./myprogram"
argv[1] is the string "/tmp/somefile"
argv[2] is a NULL pointer
Although not covered by standards, on Windows and most flavours of Unix and Linux, main can have up to three arguments:
int main(int argc, char *argv[], char *envp[])
The last one is similar to argv (which is an array of strings, as described in other answers, specifying arguments to the program passed on the command line.)
But it contains the environment variables, e.g. PATH or anything else you set in your OS shell. It is null terminated so there is no need to provide a count argument.
These are for using the arguments from the command line -
argc contains the number of arguments on
the command line (including the program name), and argv is the list of
actual arguments (represented as character strings).
These are used to pass command line paramters.
For ex: if you want to pass a file name to your process from outside then
myExe.exe "filename.txt"
the command line "filename.txt" will be stored in argv[], and the number of command line parameter ( the count) will be stored in argc.
main() is a function which actually can take maximum three parameters or no parameters.
The following are the parameters that main() can take is as follows:-
1) int argc : It holds the number of arguments passed (from the command prompt) during the execution of program or you can say it is used ot keep a track of the number of variables passed during the execution of program. It cannot hold the negative value. Eg. If you pass your executable file "./a.out" then that will be considered as a parameter and hence argc value will be 0 i.e 1 value is passed.
2) char *argv[] : it is an array of character pointers which holds the address of the strings(array of characters) that are passed from the command prompt during execution of program. Eg. in above example if you wrote argv[argc] i.e argv[0] in cout then it will give ./a.out as output.
3) char*envp[] : it is also an array of character pointer which is used to hold the address of the environments variables being used in the program. Environment variables are the set of dynamic named value that can affect the way the running process will behave on the computer. For example running process want to store temporary files then it will invoke TEMP environment variables to get a suitable location.

How much memory is allocated for argv[]? [duplicate]

This question already has answers here:
where command line arguments are stored?
(4 answers)
Closed 6 years ago.
I know that the command line arguments are character arrays and that they are stored on the stack. But, I want to know actual memory allocation for of each argument. e.g. suppose I passed the directory name "/tmp" as a command line argument. This will be stored in argv[1]. But as I tested, it is allowed to change argv[1] to "/tmp/log/" (size increased) in the program. How is this possible ?
To answer your question, the total maximum size available to argument strings and the passed environment can be obtained with:
getconf ARG_MAX
from the command line or the syconf equivalent from C (see http://pubs.opengroup.org/onlinepubs/009695399/basedefs/limits.h.html for more information).
(On my Linux box, the limit is 2097152).
Your example happens to work because the arguments and the environment are realistically stored contiguously, so appending to a string will overwrite what comes after it (following arguments, or the environment).
And that's why it's a bad idea to try and expand the argv strings like that. If you want to modify them, either edit them or shrink them, but trying to expand them is a call for trouble.
On Linux, parameters are populated by create_elf_tables. For this specific platform at least, you are correct that the values are stored on the stack.
Linux only uses exactly as much memory as is necessary to store arguments and (initial) environment variables on the stack; if you try to use more than what is already there, you're overwriting something else (or crashing).
The standard states that the argv can be modified since it is a special internal.
177 — The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination, so it is allocated only what you need at the assignment or replacement.
Standard text:
http://c0x.coding-guidelines.com/5.1.2.2.1.html

Function argument evaluation order [duplicate]

This question already has answers here:
Order of evaluation in C++ function parameters
(6 answers)
Closed 7 years ago.
I'm confused about in what order function arguments are evaluated when calling a C++ function. I have probably interepreted something wrong, so please explain if that is the case.
As an example, the legendary book "Programming Windows" by Charles Petzold contains code like this:
// hdc = handle to device context
// x, y = coordinates of where to output text
char szBuffer[64];
TextOut(hdc, x, y, szBuffer, snprintf(szBuffer, 64, "My text goes here"));
Now, the last argument is
snprintf(szBuffer, 64, "My text goes here")
which returns the number of characters written to the char[] szBuffer. It also writes the text "My text goes here" to the char[] szBuffer.
The fourth argument is szBuffer, which contains the text to be written. However, we can see that szBuffer is filled in the fifth argument, telling us that somehow is the expression
// argument 5
snprintf(szBuffer, 64, "My text goes here")
evaluated before
// argument 4
szBuffer
Okay, fine. Is this always the case? Evaluation is always done from right to left? Looking at the default calling convention __cdecl:
The main characteristics of __cdecl calling convention are:
Arguments are passed from right to left, and placed on the stack.
Stack cleanup is performed by the caller.
Function name is decorated by prefixing it with an underscore character '_' .
(Source: Calling conventions demystified)
(Source: MSDN on __cdecl)
It says "Arguments are passed from right to left, and placed on the stack".
Does this mean that the rightmost/last argument in a function call is always evaluated first? Then the next to last etc? The same goes for the calling convention __stdcall, it also specified a right-to-left argument passing order.
At the same time, I came across posts like this:
How are arguments evaluated in a function call?
In that post the answers say (and they're quoting the standard) that the order is unspecified.
Finally, when Charles Petzold writes
TextOut(hdc, x, y, szBuffer, snprintf(szBuffer, 64, "My text goes here"));
maybe it doesn't matter? Because even if
szBuffer
is evaluated before
snprintf(szBuffer, 64, "My text goes here")
the function TextOut is called with a char* (pointing to the first character in szBuffer), and since all arguments are evaluated before the TextOut function proceeds it doesn't matter in this particular case which gets evaluated first.
In this case it does not matter.
By passing szBuffer to a function that accepts a char * (or char const *) argument, the array decays to a pointer. The pointer value is independent of the actual data stored in the array, and the pointer value will be the same in both cases no matter whether the fourth or fifth argument to TextOut() gets fully evaluated first. Even if the fourth argument is fully evaluated first, it will evaluate as a pointer to data -- the pointed-to data is what gets changed, not the pointer itself.
To answer your posed question: the actual order of argument evaluation is unspecified. For example, in the statement f(g(), h()), a compliant compiler can execute g() and h() in any order. Further, in the statement f(g(h()), i()), the compiler can execute the three functions g, h, and i in any order with the constraint that h() gets executed before g() -- so it could execute h(), then i(), then g().
It just happens that in this specific case, evaluation order of arguments is wholly irrelevant.
(None of this behavior is dependent on calling convention, which only deals with how the arguments are communicated to the called function. The calling convention does not address in any way the order in which those arguments are evaluated.)
I would agree that it depends on the calling convention, because the standard does not specify the order.
See also: Compilers and argument order of evaluation in C++
And I would also agree that is does not matter in this case, because the snprintf is always evaluated before the TextOut - and the buffer gets filled.

getopt_long() function with custom argc and argv

I am having trouble using getopt_long() function with custom argc and argv.
I receive my arguments in a string instead of the real command line args. Then a new_argc and new_argv was built from this string to be used with getopt_long(). But getopt_long() fails on the first call itself. returns EOF and optarg = NULL.
string is "-c 10.30.99.41"
new_argc = 3
new_argv[0]=>./prog_name
new_argv[1]=>-c
new_argv[2]=>10.30.99.41
getopt_long works OK for me if I pass command line args. So my short and long options are correct. But if I pass the new_argc and new_argv it fails.
I am sure my short and long options are right and the argv is NULL terminated. I apologize I cant post more code here.
I doubt if getopt_long can be used with a custom argc and argv. I suspect it works only with a real argc and argv because it must be referencing some other code in libc related to argc,argv. Any comments?
option = getopt_long( new_argc, new_argv, short_options, long_options, NULL );
EDIT:
"The variable optind is the index of the next element to be processed in argv. The system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector."
So, yes. You can use getopt_long to scan the arguments or another argument list again. However, if someone has called getopt_long previously, you have to set the global optind variable to back to 1.
Remember that the argv in main() is NULL terminated and argc long, that is; argv[argc] == NULL. So you likely have to make sure the last element in your own new_argv is a NULL pointer.
(Note, please show all the relevant code when posting, it's hard to guess what the error is, e.g. showing what short_options, long_option is, how you actually build your new_argv, variable declarations etc.)

Why check if (*argv == NULL)? [duplicate]

This question already has answers here:
When can argv[0] have null?
(4 answers)
Closed 6 years ago.
In the data structures class that I am currently taking, we have been tasked with writing a web crawler in C++. To give us a head start, the professor provided us with a program to get the source from a given URL and a simple HTML parser to strip the tags out. The main function for this program accepts arguments and so uses argc/argv. The code used to check for the arguments is as follows:
// Process the arguments
if (!strcmp(option, "-h"))
{
// do stuff...
}
else if (!strcmp(option, ""))
{
// do stuff...
}
else if (!strcmp(option, "-t"))
{
// do stuff...
}
else if (!strcmp(option, "-a"))
{
// do stuff...
}
if ( *argv == NULL )
{
exit(1);
}
Where "option" has been populated with the switch in argv[1], and argv[2] and higher has the remaining arguments. The first block I understand just fine, if the switch equals the string do whatever based on the switch. I'm wondering what the purpose of the last if block is though.
It could be that my C++ is somewhat rusty, but I seem to recall *argv being equivalent to argv[0], basically meaning it is checking to make sure arguments exist. Except I was under the impression that argv[0] always (at least in most implementations) contained the name of the program being run. It occurs to me that argv[0] could be null if argc is equal to 0, but searching around on Google I couldn't find a single post determining whether or not that is even possible.
And so I turn to you. What exactly is that final if block checking?
EDIT: I've gone with the reasoning provided in the comments of the selected answer, that it may be possible to intentionally cause argv[0] to become NULL, or otherwise become NULL based on an platform-specific implementation of main.
3.6.1/2:
If argc is non-zero those arguments
shall be provided in argv[0] though
... and argv[0] shall be the pointer
to the initial character of a NTMBS
that represents the name used to
invoke the program or "". The value of
argc shall be nonnegative. The value
of argv[argc] shall be 0.
Emphasis mine. argc is only guaranteed non-negative, not non-zero.
This is at entry to main. It's also possible that //do stuff modifies the value of argv, or the contents of the array it points to. It's not entirely unheard of for option-handling code to shift values off argv as it processes them. The test for *argv == null may therefore be testing whether or not there are any command-line arguments left, after the options have been removed or skipped over. You'd have to look at the rest of the code.
argc will provide you with the number of command line arguments passed. You shouldn't need to check the contents of argv too see if there are not enough arguments.
if (argc <= 1) { // The first arg will be the executable name
// print usage
}
Remembering just how portable C is, it might not always be running on a standard platform like Windows or Unix. Perhaps it's some micro-code inside your washing machine running on some cheap, hacked environment. As such, it's good practice to make sure a pointer isn't null before dereferencing it, which might have led to the question.
Even so, you're correct. *argv is the same as argv[0], and argv is supposed to be initialized by the environment, if it's provided.
just a speculation.
what if your professor is referring to this ??
while(*++argv !=NULL)
printf("%s\n",*argv);