vendredi 2 février 2018

What's wrong with my implementation of std::strcopy? (segmentation fault)

I'm encountering a run time error attempting to use std::strcopy with elements in a vector of std::string.

There is no problem with the vector. I have higher level functions that work without a hitch. I'm running into an issue with my low level function char ** argv().

Here is a chunk of a class I'm writing. I think I've posted enough of it for the question. I'm trying to focus attention to the problem.

At runtime, the line indicated in the code below blows up.

class ArgParser{
    public:

        ... MORE CODE ...

        int & argc()
        {
            argc_ = exePath_.empty() ? 0 : 1 + args_.size();
            return argc_;
        }

        char ** argv()
        {
            const int argCount = argc();
            if( argCount==0 ) return argv_;
            if( argv_ )
            {
                for( int i=0; i < argCount; i++ )
                    delete argv_[i];
                delete argv_;
            }
            argv_ = new char*[argCount];
            *(argv_ + 0)=new char[ exePath().size() ];
            strcpy( *(argv_ + 0), exePath_.c_str() );
            int i=1;
            for( auto &arg : args_ )
            {
                *(argv_ + i++)=new char[ arg.size() ];
                strcpy( *(argv_ + i++), arg.c_str() ); // SEG FAULT!
            }
            return argv_;
        }
    private:
        int argc_;
        char **argv_;
        std::vector <std::string> args_;
        std::string exePath_;
};

Aucun commentaire:

Enregistrer un commentaire