简单 C++ 程序中的堆损坏

Heap corruption in simple C++ program

我写了一个简单的C++程序,代码如下:

// Вариант 72, задача 2.18
#include <iostream>

#define lint long long int

using std::cin;
using std::cout;

void input(lint arr[], lint arrLen) {
    for (lint i = 0; i < arrLen; ++i) {
        cout << "arr[" << i << "] = ";
        cin >> arr[i];
    }
}

void output(lint arr[], lint arrLen) {
    for (lint i = 0; i < arrLen; ++i) {
        cout << "newArr[" << i << "] = " << arr[i] << '\n';
    }
}

bool isNumberInArray(const lint arr[], lint arrLen, lint number) {
    bool isNumberPresent = false;
    for (lint i = 0; i < arrLen; ++i) {
        if (arr[i] == number) isNumberPresent = true;
    }
    return isNumberPresent;
}

void process(const lint arr[], lint arrLen, lint newArr[], lint &newArrLen, lint m, lint M) {
    newArrLen = 0;
    for (lint i = M; i >= m; --i) {
        if (!isNumberInArray(arr, arrLen, i)) {
            newArr[newArrLen] = i;
            ++newArrLen;
        }
    }
}

int main() {
    lint arrLen, m, M;

    cout << "Enter m\n> ";
    cin >> m;
    cout << "Enter M\n> ";
    cin >> M;
    cout << "Enter array length\n> ";
    cin >> arrLen;

    lint *arr = new lint[arrLen];

    cout << "Enter array elements:\n";
    input(arr, arrLen);

    lint *newArr = new lint[arrLen], newArrLen;

    process(arr, arrLen, newArr, newArrLen, m, M);

    cout << "\nResults:\n";
    output(newArr, newArrLen);

    delete[] arr;
    delete[] newArr;
    return 0;
}

当我使用 MSVC (x86 | Debug) 和 运行 编译它时,它正常工作并产生所需的结果,但执行后显示以下错误:

我尝试使用 g++ 在 WSL 下编译程序并使用 Valgrind 对其进行调试。这是我得到的:

root@seiba-laptop : /mnt/c/Users/saber-nyan/source/repos/Project1/Project1
[130] # g++ ./main.cpp -O0 -ggdb -o ./main

root@seiba-laptop : /mnt/c/Users/saber-nyan/source/repos/Project1/Project1
[0] # valgrind ./main
==316== Memcheck, a memory error detector
==316== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==316== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==316== Command: ./main
==316==
==316== error calling PR_SET_PTRACER, vgdb might block
Enter m
> 1
Enter M
> 5
Enter array length
> 2
Enter array elements:
arr[0] = 4
arr[1] = 2
==316== Invalid write of size 8
==316==    at 0x1093A4: process(long long const*, long long, long long*, long long&, long long, long long) (main.cpp:34)
==316==    by 0x1094E4: main (main.cpp:57)
==316==  Address 0x4d60560 is 0 bytes after a block of size 16 alloc'd
==316==    at 0x483850F: operator new[](unsigned long) (vg_replace_malloc.c:423)
==316==    by 0x1094BA: main (main.cpp:55)
==316==

Results:
newArr[0] = 5
newArr[1] = 3
==316== Invalid read of size 8
==316==    at 0x1092B7: output(long long*, long long) (main.cpp:18)
==316==    by 0x10950A: main (main.cpp:60)
==316==  Address 0x4d60560 is 0 bytes after a block of size 16 alloc'd
==316==    at 0x483850F: operator new[](unsigned long) (vg_replace_malloc.c:423)
==316==    by 0x1094BA: main (main.cpp:55)
==316==
newArr[2] = 1
==316==
==316== HEAP SUMMARY:
==316==     in use at exit: 0 bytes in 0 blocks
==316==   total heap usage: 5 allocs, 5 frees, 74,784 bytes allocated
==316==
==316== All heap blocks were freed -- no leaks are possible
==316==
==316== For counts of detected and suppressed errors, rerun with: -v
==316== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

问题是什么以及如何解决?

据我了解,您试图构建一个包含原始数组中不存在的值的新数组。在您的情况下,您首先构建 [4,2] 并尝试构建 [5,3,1],因为 [4,2] 中不存在的 M=5,m=1 之间的值是 [5,3,1]。

您的问题是您首先将 newArr 构建为长度为 2 的数组(与 arr 的长度相同)。但是您不能将 3 个值放入大小为 2 的数组中。

==316== Invalid write of size 8
==316==    at 0x1093A4: process(long long const*, long long, long long*, long long&, long long, long long) (main.cpp:34)
==316==    by 0x1094E4: main (main.cpp:57)
==316==  Address 0x4d60560 is 0 bytes after a block of size 16 alloc'd
==316==    at 0x483850F: operator new[](unsigned long) (vg_replace_malloc.c:423)
==316==    by 0x1094BA: main (main.cpp:55)

Invalid write of size 8 表示您试图在某个错误地址写入 long long int

Address 0x4d60560 is 0 bytes after a block of size 16 alloc'd 表示 valgrind 检测到您的错误写入位于大小为 16 的内存块的末尾,恰好是两个 long long ints 数组的大小。

问题是您的 newArr 不一定有足够的 space 来容纳所有 long long int;这取决于 M 和 m 的值,它们决定了 process(...) 中的 for 循环将经历多少次迭代以及存储在 arr.

中的值

要修复它,请在此处的这一行中:

  • lint *newArr = 新 lint[arrLen], newArrLen;

分配 (M - m + 1),而不是 arrLen 数量的新 lints。

您还应该确保 M > m