Is it possible to change argv or do I need to create an adjusted copy of it?

后端 未结 8 1039
长情又很酷
长情又很酷 2020-11-29 09:01

My application has potentially a huge number of arguments passed in and I want to avoid the memory of hit duplicating the arguments into a filtered list. I would like to fi

8条回答
  •  悲哀的现实
    2020-11-29 09:34

    The original allocation of argv is left as a compiler/runtime choice. So it may not be safe to modify it willy-nilly. Many systems build it on the stack, so it is auto-deallocated when main returns. Other build it on the heap, and free it (or not) when main returns.

    It is safe to change the value of an argument, as long as you don't try to make it longer (buffer overrun error). It is safe to shuffle the order of the arguments.

    To remove arguments you've preprocessed, something like this will work:

    ( lots of error conditions not checked for, "--special" other that first arg not checked for, etc. This is, after all, just a demo-of-concept. )

    int main(int argc, char** argv)
    {
        bool doSpecial = false; // an assumption
        if (0 == strcmp(argv[1], "--special"))
        {
            doSpecial = true; // no longer an assumption
            // remove the "--special" argument
            //  but do copy the NULL at the end.
            for(int i=1; i

    But see this for full manipulation: (the part of the libiberty library that is used to manipulates argv style vectors)

    http://www.opensource.apple.com/source/gcc/gcc-5666.3/libiberty/argv.c

    It is licensed GNU LGPL.

提交回复
热议问题