Luís Lucas
Luís Lucas

Reputation: 21

Heap Corruption Detected Malloc() Free()

Why am i getting an error "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;
}

Upvotes: 0

Views: 1073

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49803

The argument to malloc is the number of bytes to allocate; you have provide the number of ints you want allocated. Do malloc(elements * sizeof(int)) to fix that.

Upvotes: 2

Related Questions