簡體   English   中英

const char *在循環期間更改值

[英]const char * changing value during loop

我有一個通過const char *迭代的函數,並使用該字符將對象添加到std::map實例(如果它是一系列公認的字符之一)。

#define CHARSEQ const char*

void compile(CHARSEQ s) throw (BFCompilationError)
{
     std::cout << "@Receive call " << s << std::endl;

     for(int i = 0; s[i] != '\0'; i++)
     {
         if (std::string("<>-+.,[]").find_first_of(s[i]) == std::string::npos)
         {
             throw BFCompilationError("Unknown operator",*s,i);
         }
         std::cout << "@Compiling: " << s[i] << std::endl;
         std::cout << "@address s " << (void*)s << std::endl;
         std::cout << "@var s " << s << std::endl;
         controlstack.top().push_back(opmap[s[i]]);
     }
 }

傳遞的字符序列為"++++++++++." 對於前三個迭代,打印語句顯示預期的值“ +”,“ +”和“ +”,而s的值繼續為“ +++++++++++”。 但是,在第四次迭代中, s變得混亂,產生諸如'Ð''öê''cR ''œk'類的奇怪值以及許多其他字符序列。 如果刪除引發異常的行並允許循環繼續,則s的值不會再次更改。

其他函數可以訪問s但是由於這不是多線程程序,所以我看不出為什么會如此。 我對s為什么在變化並不感到困惑,但是為什么它僅在第四次迭代中發生變化。

我搜索了SO,似乎唯一與相關的帖子是帖子,但它仍然無法回答我的問題。 (研究一直很困難,因為搜索“ const char *不斷變化的價值”或類似的術語僅僅涉及數百篇關於const的部分的帖子 )。

最后,我知道我可能應該使用std::string ,如果沒有答案,我會使用它,但是我仍然想了解這種行為。

編輯:

這是調用此函數的代碼。

CHARSEQ text = load(s);

std::cout << "@Receive load " << text << std::endl;

try
{
    compile(text);
}
catch(BFCompilationError& err)
{
    std::cerr << "\nError in bf code: caught BFCompilationError @" << err.getIndex() << " in file " << s << ":\n";
    std::cerr << text << '\n';
    for(int i = 0; i < err.getIndex(); i++)
    {
        std::cerr << " ";
    }
    std::cerr << "^\n";
    std::cerr << err.what() << err.getProblemChar() << std::endl;
    return 1;
}

load在哪里:

CHARSEQ load(CHARSEQ fname)
{
    std::ifstream infile (fname);
    std::string data(""), line;
    if (infile.is_open())
    {
    while(infile.good())
    {
        std::getline(infile,line);
        std::cout << "@loading: "<< line << '\n';
        data += line;
    }
    infile.close();
}
else
{
    std::cerr << "Error: unable to open file: " << fname << std::endl;
}

return std::trim(data).c_str();

}

並且文件fname++++++++++. 展開,使得每行只有一個字符。

編輯2:

這是控制台輸出的示例:

@loading: +
@loading: +
@loading: +
@loading: +
@loading: + 
@loading: +
@loading: +
@loading: +
@loading: +
@loading: +
@loading: .
@Receive load ++++++++++.
@Receive call ++++++++++.
@Compiling: +
@address s 0x7513e4
@var s ++++++++++.
@Compiling: +
@address s 0x7513e4
@var s ++++++++++.
@Compiling: +
@address s 0x7513e4
@var s ++++++++++.
@Compiling: 
@address s 0x7513e4
@var s ßu

Error in bf code: caught BFCompilationError @4 in file bf_src/Hello.txt:
ßu
^
Unknown operatorß

您的load功能有缺陷。 c_str()返回的const char*指針僅在基礎std::string對象存在之前有效。 但是dataload的局部變量,返回后將被清除。 它的緩沖區不會被零覆蓋,而是保留為空閑內存。 因此,在返回后立即打印出該值很可能會起作用,但是您的程序可能會將新值放在該值中,並且指針所指向的值將更改。

我建議使用std::string作為load的返回值來解決。

暫無
暫無

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

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