简体   繁体   English

C ++中奇怪的cout行为

[英]Weird cout behavior in C++

I am getting some weird behavior when using cout in my programm, which is similar to the following: 在程序中使用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;
    }
}
...

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. 基本上,该程序会创建一个tar文件,然后使用gzip对其进行压缩,这不是100%的实际代码,因此它可能不会给出与我收到的相同的奇怪行为。

If I removed the first cout << "TAROUT: " << tarout << endl; 如果我删除了第一个cout << "TAROUT: " << tarout << endl; the second cout << "TAROUT: " << tarout << endl; 第二个cout << "TAROUT: " << tarout << endl; would return nothing and the temporary file would not get removed, why is that? 不会返回任何内容,并且不会删除临时文件,这是为什么?

new/malloc do not initialize memory, so I'm fairly certain that you have no NULL terminator at the end of tarout. new / malloc不会初始化内存,因此我可以肯定地说,在tarout的末尾没有NULL终止符。

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. 我怀疑您是通过调试器运行原始代码还是只是打印出*(tarout + 5),您会发现那里没有'0'。

Given your comments regrading the use of std::string, I would write: 鉴于您的意见重新使用了std :: string,我将这样写:

const char * file_ext = ".temp";

// no magic numbers...and an obvious + 1 for null terminator
size_t len = strlen(output)+strlen(file_ext)+1;

char *tarout = new char[len];

memset(tarout, 0, len);

strcpy(tarout, output);
strcat(tarout, file_ext);

// If you feel memset is wasteful, you can use
*(tarout+len-1) = 0;

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM