我有一个定制的“迷你 shell ”代码,我在其中将用户提供的字符串解析为子进程中终端中的单个单词。
子代码如下:
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'
问题 是,每当我将输入字符串的一个词分配给 args[i]
时,所有从索引 0 到 (i - 1)
也被赋予相同的值。 So,如果用户输入,比方说,ls asd dajd adakjs
,那么我最终(在 while 循环结束时)得到所有 args[i]
的值为“adakjs
”,如以下输出所示(cout
语句仅用于调试目的):
Inside loop 0 lsbefre cndition aftr ass 0 ls Before Assignment: 0 lskwe 1 asdbefre cndition aftr ass After Assignment: 0 asdeefe 1 asd 0 asd 1 asd Before Assignment: 1 asdkwe 2 dajdbefre cndition aftr ass After Assignment: 1 dajdeefe 2 dajd 0 dajd 1 dajd 2 dajd 3 adakjs Outside loop adakjs 0 adakjs 1 adakjs 2 adakjs 3 adakjs adakjs Unknown command
为什么会这样?我如何修改我的代码,以便在 while 循环结束时,每个单词都存储到 arg[i]s 中?提前致谢!
最佳答案
有问题的行是这样的:
args[i] = const_cast<char*>((command.substr(prev_pos, (pos - prev_pos))).c_str());
substr
函数返回一个字符串对象,您从中获得一个指针,然后该字符串对象被破坏,留下一个指向数据的杂散指针不再存在。这将导致 undefined behavior .
您需要为字符串分配内存以使其永久化。
关于c++ - 子进程中的数组分配无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29140383/