Question Details

No question body available.

Tags

c

Answers (2)

Accepted Answer Available
Accepted Answer
January 7, 2026 Score: 5 Rep: 610,038 Quality: Expert Completeness: 60%

First, your main() function is declared wrong. The argc parameter needs to be int instead of int.

Second, while (++argv) is an infinite loop, so you end up going out of bounds of the argv array. Your loop condition is not dereferencing argv to test whether it is currently pointing at a valid string before the loop body then tries to process that string. So, you end up going past the end of the array into surrounding memory, processing garbage until it eventually hits memory it can't access anymore, causing the segfault.

Try this instead:

void switch_argument (char const argv[])
{
    char const arg;

while ((arg =
(++argv)) != NULL) { if (arg[0] == '-') { switch (arg[1]) { case 'p': printf("Pack.\n"); break; case 'u': printf("Unpack.\n"); break; default: Helper(); } } } }

int main(int argc, char const argv[]) { // Check for 3 arguments if (argc >= 3) { switch_argument(argv); } else { printf("Too few arguments.\n"); Helper(); }

return 0; }

Alternatively, argc tells you exactly how many strings are in the argv array, so you don't need to rely on argv being null-terminated. You can instead pass argc to your switch_argument() function and use it in the for loop, eg:

void switch_argument (int argc, char const argv[])
{
    for (int idx = 1; idx < argc; ++idx)
    {
        char const arg = argv[idx];

if (arg[0] == '-') { switch (arg[1]) { case 'p': printf("Pack.\n"); break; case 'u': printf("Unpack.\n"); break; default: Helper(); } } } }

int main(int argc, char const
argv[]) { // Check for 3 arguments if (argc >= 3) { switch_argument(argc, argv); } else { printf("Too few arguments.\n"); Helper(); }

return 0; }
January 7, 2026 Score: 2 Rep: 494,590 Quality: Medium Completeness: 60%

As noted in the comments, argv[argc] == 0, so in theory, it's possible to loop through all the arguments by incrementing argv until you reach a null pointer.

That said, I think @Remy is basically correct anyway. Even at best, this is a clumsy, error-prone way of iterating through the command line arguments. For example, the main problem you're currently having is that your loop condition checks that argv is a non-null pointer, but inside your loop you try to use argv[1].

This leads to a couple of problems. First, it skips not only the program name in argv[0], but also the first flag in argv[1]. And when argv is pointing at the last argument that was passed, argv[1] is a null pointer, so trying to use it is what's causing your core dump.

Assuming the C++ tag is accurate, I'd do something like this:

#include 
#include 
#include 

void switch_argument(std::vector const &args) { for (auto const &arg : args) { if (arg[0] == '-') { switch(arg[1]) { case 'p': std::cout