0

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 << "TAROUT: " << tarout << endl;のファイルを削除すると、2 番目cout << "TAROUT: " << tarout << endl;のファイルは何も返されず、一時ファイルが削除されません。なぜですか?

4

1 に答える 1

3

new/malloc はメモリを初期化しないので、tarout の最後に NULL ターミネータがないことは確かです。

元のコードをデバッガーで実行するか、単に *(tarout+5) を出力すると、そこに「0」がないことがわかると思います。

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;

...
于 2011-02-25T03:52:21.817 に答える