0

Here is my function:

void Tetris::place_square(int* coords,char type){
    if (coords[1]>heights[coords[0]]){
        char* old=data[coords[0]];
        data[coords[0]]=new char[coords[1]];
        for (unsigned int i=0; i<heights[coords[0]]; ++i){
            data[coords[0]][i]=old[i];
        }
        for (unsigned int i=heights[coords[0]]; i<coords[1]; ++i){
            data[coords[0]][i]=" "[0];
        }
        data[coords[0]][coords[1]-1]=type;
        heights[coords[0]]=coords[1];
        delete old;
    } else {
        data[coords[0]][coords[1]-1]=type;
    }
}

It compiles fine but when I try to run it i get malloc: *** error for object 0x7fff503e0020: pointer being freed was not allocated

I believe the problem is delete old; but I don't know how to fix it.

trincot
  • 317,000
  • 35
  • 244
  • 286
Dan G.
  • 982
  • 1
  • 8
  • 20
  • How do you fill `data` and `coords` before calling `place_square`? – nullptr Feb 20 '15 at 23:38
  • `data[coords[0]];` was initialized with `data[i]=new char[0];` coords is just an array of size two with two ints `coords[0]` is always a valid index for data – Dan G. Feb 21 '15 at 00:46

2 Answers2

2

Looking at this section:

char* old=data[coords[0]];
data[coords[0]]=new char[coords[1]];

I'm not sure what is in your data array, but it looks like you are assigning a pointer which has not yet been initialized.

If you are initializing with

data[i]=new char[0];

Then you should also be deleting with delete[].

Joel
  • 4,732
  • 9
  • 39
  • 54
  • No, `data[coords[0]];` was initialized with `data[i]=new char[0];` – Dan G. Feb 21 '15 at 00:44
  • Is there a reason you are initializing your array that way? That effectively just doubles the number of pointers you have to free later. Take a look at [this question](http://stackoverflow.com/questions/1087042/c-new-int0-will-it-allocate-memory) concerning allocations of size 0. – Joel Feb 21 '15 at 00:52
1

The address indicates that data[coords[0]] was previously pointing to an automatic variable. You can only use delete on things that were allocated by new.

Also, you should use delete[] when things were allocated by new[] as they are in this example.

To fix this you will need to review the initialization of data and any code that might update data[x] . It is also possible that coords[0] is out of bounds for data.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • `data[coords[0]];` was initialized with `data[i]=new char[0];` – Dan G. Feb 21 '15 at 00:45
  • @DanG. the error message indicates that it wasn't . To get better help post a [MCVE](http://stackoverflow.com/help/mcve). – M.M Feb 21 '15 at 00:55