【发布时间】:2020-08-02 03:11:20
【问题描述】:
为什么我收到错误“检测到堆损坏:在 0x 的正常块 (#187) 之后...”
#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;
}
【问题讨论】:
-
您正在为
elementsbytes分配足够的空间,但试图使用足够的空间来存储elementsints。跨度>
标签: c++ malloc heap-memory free corruption