Search code examples
c++pointersheap-corruption

C++ Heap corruption after simple action


I can't get why simple actions with my array corrupt the heap.

For example, this code works fine:

double *matrix = (double*)(malloc(50));

free(matrix);

Then, I try to modify some of the elements of this array like this:

double *matrix = (double*)(malloc(50));

for (int i = 0; i < 20; matrix++, i++) {
    *matrix = (double)i;
}

free(matrix);

The problem is that even this code is not working at all. (VS tells me that the heap was corrupted). Probably it is a stupid mistake, but I am new to all this actions with pointers.

UPDATE

Now my code looks like this:

double *matrix = (double*)malloc(sizeof(double) * 50);

But I got this error message:

enter image description here


Solution

  • Your code modified the pointer "matrix" before you free it, which I believe is an undefined behavior.

    No offense, but I suggest you get a good book about c++. "malloc" is not the preferred way for dynamic memory allocation in c++.

    Anyway, if you would like to access the memory block as an array, the preferable way to do it is to use operator[]:

    for (int i = 0; i < 20; i++) {
        matrix[i] = (double)i;
    } 
    

    And yes, as @Hernantas mentioned, if you want to allocate a space for 50 double objects, use

    myVar = malloc (sizeof(double) * 50);