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

问题描述 投票:0回答:1

为什么我会收到错误消息“检测到堆损坏:在正常块(#187)处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;
}
c malloc heap free corruption
1个回答
0
投票

malloc的参数是要分配的字节数;您已经提供了要分配的int的数量。

© www.soinside.com 2019 - 2024. All rights reserved.