C++ 中奇怪的 cout 行为
在我的程序中使用 cout
时,我遇到了一些奇怪的行为,类似于以下内容:
...
char *input = realpath(argv[1], NULL);
char *output = argv[2];
char *tarout = new char[strlen(output)+6];
strcpy(tarout, output);
strcat(tarout, ".temp");
cout << "Tarout: " << tarout << endl;
int tRet = tarball(input, tarout);
if(tRet != 1) {
cerr << "Error: Could not compress directory!\nHalting package creation!" << endl;
return 0;
}
int gRet = gzip(tarout, output);
if(gRet != 1) {
cerr << "Error: Could not compress directory!\nHalting package creation!" << endl;
return 0;
} else {
cout << "TAROUT: " << tarout << endl;
if((remove(tarout))!=0) {
cerr << "Warning: Could not delete temporary file!" << endl;
return 0;
}
}
...
基本上这个程序创建一个 tar 文件,然后用 gzip 压缩它,这不是 100% 的实际代码,所以它可能不会产生与我收到的相同的奇怪行为。
如果我删除了第一个 cout << “塔鲁特:”<<芋头<< endl;
第二个cout << “塔鲁特:”<<芋头<< endl;
不会返回任何内容,并且临时文件不会被删除,这是为什么?
I am getting some weird behavior when using cout
in my programm, which is similar to the following:
...
char *input = realpath(argv[1], NULL);
char *output = argv[2];
char *tarout = new char[strlen(output)+6];
strcpy(tarout, output);
strcat(tarout, ".temp");
cout << "Tarout: " << tarout << endl;
int tRet = tarball(input, tarout);
if(tRet != 1) {
cerr << "Error: Could not compress directory!\nHalting package creation!" << endl;
return 0;
}
int gRet = gzip(tarout, output);
if(gRet != 1) {
cerr << "Error: Could not compress directory!\nHalting package creation!" << endl;
return 0;
} else {
cout << "TAROUT: " << tarout << endl;
if((remove(tarout))!=0) {
cerr << "Warning: Could not delete temporary file!" << endl;
return 0;
}
}
...
Basically this program creates a tar file and then compresses it with gzip, this is not the 100% actual code so it may not give the same odd behavior as have I been receiving.
If I removed the first cout << "TAROUT: " << tarout << endl;
the second cout << "TAROUT: " << tarout << endl;
would return nothing and the temporary file would not get removed, why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
new/malloc 不初始化内存,所以我相当确定 tarout 末尾没有 NULL 终止符。
我怀疑如果您通过调试器运行原始代码或只是打印出 *(tarout+5),您会看到那里没有“0”。
鉴于您对 std::string 的使用进行重新评级的评论,我会写:
new/malloc do not initialize memory, so I'm fairly certain that you have no NULL terminator at the end of tarout.
I suspect if you run your original code through a debugger or simply print out *(tarout+5), you would see that there is no '0' there.
Given your comments regrading the use of std::string, I would write: