簡體   English   中英

C++ 指針值意外更改為 0x1 - 如何防止這種情況

[英]C++ Pointer value changing to 0x1 unexpectly - how to prevent this

我正在嘗試調試一個問題,其中指針的值在 class 的成員 function 中意外更改為0x1 我意識到這可能是一個常見問題,並且由於堆棧上的某些變化。 但是我沒有足夠的經驗來確切地知道原因是什么以及我應該在設計中進行哪些更改來修復它。 任何好的意見或建議將不勝感激。

當我嘗試查找鍵為 mlir::Operation* 的另一個容器(在不同的函數中)時,它將失敗,因為指針的地址已更改。

我有 class 稱為Schedule ,看起來像這樣。

class Schedule {

using schedulable_ops_t = std::list<mlir::Operation*>;
typedef typename schedulable_ops_t::iterator schedulable_ops_iterator_t

void next_schedulable_operation();

mlir::Operation* schedulable_op_;
schedulable_ops_t candidates_;

}

成員 function next_schedulable_operation()如下所示:

bool Schedule:next_schedulable_operation() {

    schedulable_op_ = NULL;

    do {
        schedulable_ops_iterator_t op_itr = find_schedulable_op();

        if (is_valid_op(op_itr)) {
        
            std::cout << "The pointer value is " << *op_itr << std::endl;
            candidates_.erase(op_itr);
            std::cout << "The pointer value is " << *op_itr << std::endl;
            schedule_operation(*op_itr);
            std::cout << "The pointer value is " << *op_itr << std::endl;

            schedulable_op_ = *op_itr;  
            std::cout << "The pointer value is " << *op_itr << std::endl;

        }
    }

}

我得到的 output 是:

The pointer value is 0x555555695650
The pointer value is 0x555555695650
The pointer value is 0x1

當我省略最后一個 cout 語句時,它不會改變價值,但我認為這只是一個巧合。


評論后的變化:

bool Schedule::scheduleOperation(mlir::Operation*& op) {
        //Schedule the operation
}

bool Schedule::next_schedulable_operation() {
    
    schedulable_op_ = NULL;
    
     do {
        schedulable_ops_iterator_t op_itr = find_schedulable_op();
    
        if (is_valid_op(op_itr)) {

            mlir::Operation* &op = *op_itr;
            
            candidates_.erase(op_itr);
            schedule_operation(op);
            schedulable_op_ = op;  
            
        }
}
        std::cout << "The pointer value is " << *op_itr << std::endl;
        candidates_.erase(op_itr);
        std::cout << "The pointer value is " << *op_itr << std::endl;

在完成前兩行之后, op_itr變得無效。 一旦你執行*op_itr ,你就會觸發未定義的行為。

https://en.cppreference.com/w/cpp/container/list/erase

對已擦除元素的引用和迭代器無效。

實際上,如果我正確理解您的代碼,這意味着您無法安排已刪除的操作。

暫無
暫無

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

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