为什么不满足我的C ++ for循环总是执行?

时间:2020-04-05 16:15:22

标签: c++ for-loop indexing segmentation-fault

来自Java,我是C ++的新手。 尽管i的初始值超过了n - 1,但是我无法弄清楚为什么下面的for循环总是执行。

    int maxProfit(vector<int>& prices) {
        const int n = prices.size();
        int profit = 0;
        for(size_t i = 0; i < n - 1; i++) {
            cout << "i: " + to_string(i) + ", n - 1: " + to_string(n - 1) + '\n';
            const int diff = prices[i + 1] - prices[i];
            if(diff > 0) { profit += diff; }
        }
        return profit;
    }

我得到的输出(由于print语句)是: i: 0, n - 1: -1,后跟:

AddressSanitizer:DEADLYSIGNAL
=================================================================
==32==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000004 (pc 0x000000382c25 bp 0x7ffd70e65f70 sp 0x7ffd70e65d00 T0)
==32==The signal is caused by a READ memory access.
==32==Hint: address points to the zero page.
    #3 0x7f6ee7f0682f  (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
AddressSanitizer can not provide additional info.
==32==ABORTING

也许我什么都没看到,但是有人可以告诉我为什么for循环会被执行,尽管违反了for循环的条件吗?

我不确定这是哪个C ++版本。这来自LeetCode的在线编辑器。

1 个答案:

答案 0 :(得分:4)

Java没有无符号类型,而C ++没有。如果n == 0,则n - 1在数学上是-1,但是-1不是无符号值。在这种情况下,发生的结果是环绕-1实际上等于最大可能的无符号值。将您的代码更改为此,以获得预期结果

for(size_t i = 0; i + 1 < n; i++) {

现在没有负数了。