获取 int 数组的不一致堆损坏 - C++

Getting inconsistent heap corruption for int array - C++

我正在尝试以下程序,但出现堆损坏,这是预料之中的。 以下是下面的代码:

int main()
{
    int A[] = { 2,4,16,32,0,0,0,0 };
    int B[] = { 5,17,31,35 };
    int i = 0, j = 0,k=0;
    int length = sizeof(A) / sizeof(A[0]);
    int* temp = new int[length];
    while (k<length && A[k]!=0)
    {
        if (A[i] < B[j])
        {
            temp[k] = A[i];
            i++;
        }
        else
        {
            temp[k] = B[j];
            j++;
        }
        k++;
    }
    //copythe remaining items in A[] into temp.
    while (i < length && A[i] != 0)
    {
        temp[k] = A[i];
        i++; k++;
    }
    //copy the remaining items in B[] into temp.
    while (j < length)
    {
        temp[k] = B[j];
        j++; k++;
    }
    cout << "the sorted array is: ";
    for (int i = 0; i < length; i++)
    {
        cout << temp[i] << ", ";
    }
    return 0;
}

发生堆损坏,因为我正在写超出数组范围 temp。 在我看来,堆损坏应该发生在第 7244 行,我将 B[j] 分配给 temp[k] - 并且 k 超过 length(即 8) - 如下突出显示:

但是,堆损坏发生得晚得多,在第 7250 行 - 我尝试 cout<<temp[0] 的地方。 -

我有几个问题:

  1. 为什么在尝试读取 temp[0] 时会发生堆损坏 - 因为在尝试读取 temp[0] 时一切正常?
  2. 为什么堆损坏不会发生在第 7244 行本身,我将 B[j] 分配给 temp[k] 并且 k 超过 length
  3. 为什么堆损坏是间歇性的。我一开始打了4-5次heap corruption,现在打不中了?

超出数组边界的写入始终是未定义行为。话虽这么说,当您导致未定义的行为时,肯定不会发生任何不好的事情。堆损坏仅可能发生,因为它是否发生取决于相对于构成堆的数据结构临时分配的位置。

也就是说,当堆损坏发生时,它发生在您指定的行,其中 temp[k] = B[j]。该程序不会注意到堆已损坏,直到您尝试使用 cout 打印出 temp,其原因是当您尝试执行涉及的操作时堆损坏仅 "noticed"堆(例如分配或删除)。作为打印出 temp[i] 过程的一部分,cout << temp[i] << '", " 很可能在幕后进行了分配或删除,这就是导致崩溃的原因。