C++ 子进程中的数组分配无效
我有一个定制的“迷你shell”的代码,在这个代码中,我在子进程中将用户提供的字符串解析为终端中的单个单词 以下是子代码:C++ 子进程中的数组分配无效,c++,shell,C++,Shell,我有一个定制的“迷你shell”的代码,在这个代码中,我在子进程中将用户提供的字符串解析为终端中的单个单词 以下是子代码: child_pid = fork(); if (child_pid == 0) { char* args[100]; int prev_pos = 0; int pos; int i =
child_pid = fork();
if (child_pid == 0)
{
char* args[100];
int prev_pos = 0;
int pos;
int i = 0;
cout << "Inside loop" << endl;
while((pos = command.find(" ", prev_pos)) != string::npos)
{
//cout << command.substr(prev_pos, pos) << endl;
if (i >= 1)
{
cout << endl << "Before Assignment: " << i - 1 << " " << args[i - 1] <<"kwe"<< endl;
}
args[i] = const_cast<char*>((command.substr(prev_pos, (pos - prev_pos))).c_str());
cout << i << " " << args[i] <<"befre cndition aftr ass"<< endl;
//cout << command.substr(prev_pos, pos) << endl;
if (i >= 1)
{
int j=i-1;
cout << "After Assignment: "<< i - 1 << " " << args[j] <<"eefe"<< endl;
}
cout << i << " " << args[i] << endl;
if (i >= 1)
{
for (int j = 0; j <= i; j++)
{
cout << "\t" << j << " " << args[j] << endl;
}
}
prev_pos = (pos + 1);
i++;
}// 'while' loop
args[i] = const_cast<char*>((command.substr(prev_pos)).c_str());
cout << i << " " << args[i] << endl;
i++;
cout << "Outside loop" << endl << endl;
cout << *(args + 0) << endl << endl;
for (int j = 0; j < i; j++)
{
cout << j << " " << args[j] << endl;
}
args[i] = NULL;
cout << endl << endl << args[0] << endl << endl;
//execvpe(args[0], args, envp);
cout << "Unknown command\n";
exit(0);
}// 'if'
为什么会这样?如何修改代码,以便在while循环结束时,将每个单词存储到arg[I]中?提前谢谢 问题在于:
args[i] = const_cast<char*>((command.substr(prev_pos, (pos - prev_pos))).c_str());
args[i]=const_cast((command.substr(prev_pos,(pos-prev_pos))).c_str();
substr
函数返回一个string对象,其中有一个指针,然后string对象被销毁,留下一个指向不再存在的数据的散乱指针。这将导致严重的后果
您需要为字符串分配内存以使其永久化
args[i] = const_cast<char*>((command.substr(prev_pos, (pos - prev_pos))).c_str());