The problem is that you’re storing pointers into cstr
in argv
, but then you’re deleting cstr
at the end of the parse()
function. Get rid of:
delete[] cstr;
Also, you should pass argc
by reference. Otherwise, when you update it in the parse()
function it won’t update the caller’s variable. So it should be:
void parse(string str, int &argc, char *argv[])
However, you also have a memory leak. You’re creating a new cstr
each time parse
is called, but never deleting it. You should change the function to return cstr
, and have the caller delete it when they’re done with that parsed line.
char *parse(str str, int &argv, char *argv[]) {
...
return cstr;
}
Then in your main()
loop, do:
int main( void )
{
string theLine;
while (true)
{
cout << "myshell> ";
getline(cin,theLine);
cout << "Command was: " << theLine << endl;
if ((theLine == "exit") || (cin.eof()) || (theLine == "quit"))
exit(0);
char *cstr = parse(theLine, argc, argv);
cout << "argv[0] " << argv[0] << "\n";
delete[] cstr;
}
}
5
solved how to operate on global variables in c++