0

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

trincot
  • 317,000
  • 35
  • 244
  • 286
CMTV
  • 2,531
  • 2
  • 17
  • 25

2 Answers2

2

What your malloc do is allocated 50 bytes, not 50 double. Here are example of how to use malloc:

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

or if you want to use multiple (array) double then you can do it like this:

myVar = (double*)malloc (sizeof(double) * 50);
Hernantas
  • 341
  • 1
  • 6
2

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);
Lucien
  • 134
  • 5
  • Thank you. I fixed this problem. I am reading "The C programming language". I modified it because, as I understand, it do not change when modified inside other functions. For example, in function doStuff() I can write something like this: matrix+=1000; But in main function matrix still points at zero array element. Did I get it right? – CMTV Nov 22 '15 at 06:28
  • @CMTV weather the original "matrix" is modified depends on how the argument is passed. If the pointer is pass by value then the change will not affect the original variable. – Lucien Nov 22 '15 at 06:33
  • Does it mean, that by passing pointer this way: doStuff(int *p) I pass only the value of "p" (and that is why chaning it actually changes nothing in other functions) but *p still is a link to a specific array element? – CMTV Nov 22 '15 at 06:52
  • @CMTV `doStuff(int *p)` is actually passed-by-value: the value of the pointer itself is copied into the function. If you change the value of p inside doStuff (not changing what it points to), say `p = someOtherPointer`, p will point to a new position while the original pointer will remain unchanged. – Lucien Nov 22 '15 at 06:58