Are char * argv[] arguments in main null terminated?

CArgvNull Terminated

C Problem Overview


So I'm wondering if command line parameters are always null terminated? Google seems to say yes, and compiling on GCC indicates this is the case, but can I guarantee this to always be true?

int main(int argc, char** argv)
{
	char *p;

	for(int cnt=1; cnt < argc; ++cnt)
	{
		p = argv[cnt];
		printf("%d = [%s]\n", cnt, p);
	}
    return 0;
}

$ MyProgram -arg1 -arg2 -arg3
1 = -arg1
2 = -arg2
3 = -arg3

C Solutions


Solution 1 - C

Yes. The non-null pointers in the argv array point to C strings, which are by definition null terminated.

The C Language Standard simply states that the array members "shall contain pointers to strings" (C99 §5.1.2.2.1/2). A string is "a contiguous sequence of characters terminated by and including the first null character" (C99 §7.1.1/1), that is, they are null terminated by definition.

Further, the array element at argv[argc] is a null pointer, so the array itself is also, in a sense, "null terminated."

Solution 2 - C

Yes, it is always true that the arguments are null terminated strings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeviXView Question on Stackoverflow
Solution 1 - CJames McNellisView Answer on Stackoverflow
Solution 2 - CRocky PulleyView Answer on Stackoverflow