簡體   English   中英

錯誤的bool值傳遞給C ++中的函數

[英]Wrong bool value passed to function in C++

我在頭文件prog.h中定義了一個函數,它接受bool,string和double類型的幾個參數。

string createDataFolder(bool setPBC, string distribution, double timestep, double simtime, double potRange, double potStrength, 
    double particlesize, bool steric, bool ranRod, bool ranU, bool rand, double dvar, double polydiam, bool Pointq){
    //...
    if (Pointq) folder += "/pointq";
    //....
    return folder;
}

當我從prog.cpp中的main()函數內部調用函數時

string folder = createDataFolder(setPBC, distribution, timestep, simtime, urange, ustrength, 
     particlesize, includeSteric, ranRod, ranU, rand, dvar, polydiam, Pointq);

該布爾參數Pointq總是為通過false ,不管它設置為truefalse ,即使我稱之為功能

string folder = createDataFolder(setPBC, distribution, timestep, simtime, urange, ustrength, 
     particlesize, includeSteric, ranRod, ranU, rand, dvar, polydiam, true);

如果我更改了函數定義的定義並調用,那么在Pointq之后還有另一個參數,則Pointq正確傳遞,最后一個參數也是如此。

string createDataFolder(bool setPBC, string distribution, double timestep, double simtime, double potRange, double potStrength, 
    double particlesize, bool steric, bool ranRod, bool ranU, bool rand, double dvar, double polydiam, bool Pointq, bool tmp){
    //...
    if (Pointq) folder += "/pointq";
    //....
    return folder;
}

string folder = createDataFolder(setPBC, distribution, timestep, simtime, urange, ustrength, 
     particlesize, includeSteric, ranRod, ranU, rand, dvar, polydiam, Pointq, true)

如果我更改createDataFolder函數的最后兩個參數的順序,它也可以。

string createDataFolder(bool setPBC, string distribution, double timestep, double simtime, double potRange, double potStrength, 
    double particlesize, bool steric, bool ranRod, bool ranU, bool rand, double dvar, bool Pointq, double polydiam){ ... }

我假設我的代碼中有一個愚蠢的錯誤,但我不知道在哪里看,因為我沒有直覺,如何發生這樣的錯誤。 我在論壇上搜索了類似的C ++,但我找不到任何東西。

如果有人可以向我提供一些見解或指向相關主題,那將是很棒的。


編輯

這是一個在我的機器上仍會產生錯誤的最小示例

#include <iostream>


using namespace std;

void createDataFolder( double potRange, bool Pointq){
    char range[5];
    sprintf(range, "%.3f", potRange);
    cout << "in createDataFolder Pointq is " << Pointq << endl;
}

int main(int argc, const char* argv[]){    
    bool Pointq = true;
    double urange = 10;

    cout << "In main(), Pointq is " << Pointq << endl;
    createDataFolder( urange, Pointq);
    return 0;
}

在這段代碼中:

char range[5];
sprintf(range, "%.3f", potRange);

你傳遞10.0到potRange ,所以sprintf應該產生字符串“10.000”,這肯定比5長。所以你有緩沖區溢出和所有效果與UB。 在這種情況下你應該使用snprintf來避免花在調試副作用上的長時間:

char range[5];
snprintf(range, sizeof(range), "%.3f", potRange);

它不會使你的程序正確,但至少問題會變得明顯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM