检测到堆损坏 Malloc() Free()

Heap Corruption Detected Malloc() Free()

为什么我收到错误消息"Heap Corruption Detected: after normal block (#187) at 0x..."

#include <iostream>
#include <stdlib.h> 
using namespace std;

void readArray(int* a, size_t nElem) {
    for (int i = 0; i < nElem; i++) {
        cout << " arr[" << i << "]: ";
        cin >> a[i];
    }
}

int main() {
    size_t elements;
    cout << "Who many elements on the array: ";
    cin >> elements;
    int* p1 = (int*) malloc(elements); //allocating space
    readArray(p1, elements);
    free(p1); //removing allocated space
    return 0;
}

malloc的参数是要分配的字节数;您已经提供了要分配的 int 的数量。 malloc(elements * sizeof(int)) 解决这个问题。