As I understand it, you can't know for certain the length of a string in C unless it is declared as a char[]
in local scope. If it is passed as an argument, it's a char *
pointer, and you can't know the length without using strlen()
. Many other answers on Stack Overflow describe this, including this answer to "How to get the string size in bytes?".
But sometimes strings aren't null terminated, and if they aren't, you can end up looking into some other memory while trying to find the end of a string. In my own code, I should always pass the length of the string around so that I know for sure how long it is, but what about arguments to main()
?
What if bash has a bug and passes a string that is truncated or isn't null terminated? Or what if my program is called by something other than a shell, like another program that isn't as mature as the most common shells? Could my program segfault? Could I expose the memory of whatever happens to be adjacent to argv
?