【问题标题】:Heap Corruption Detected Malloc() Free()检测到堆损坏 Malloc() Free()
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多