Weird cout behavior in C++
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?
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:
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;
...
精彩评论