2

gdb backtrace:

#0  0x0040cea9 in free () from /lib/tls/i686/cmov/libc.so.6
#1  0x0033c741 in operator delete(void*) () from /usr/lib/libstdc++.so.6
#2  0x080654b6 in mesh::calculateMeanNormalsPerVertex (this=0x807d684)
    at /home/brent/Desktop/protCAD/src/math/mesh.cc:230
#3  0x0805638f in buildCubes (argc=4, argv=0xbffff3e4)
    at /home/brent/Desktop/protCAD/src/driver/executeCubes.cc:163
#4  main (argc=4, argv=0xbffff3e4)
    at /home/brent/Desktop/protCAD/src/driver/executeCubes.cc:297

Declaration and delete call in mesh.cc:

vector<vector<int> > faceIndicesPerVertex (vertexArray.size());
...
delete[] &faceIndicesPerVertex;    //line 230

I'm sure I have this wrong, but I've tried a few different ways of calling delete there, but none seem to compile except the above. What's the problem?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Rooster
  • 1,267
  • 3
  • 15
  • 23

6 Answers6

7

You don't need to delete any stack-allocated object, stack-allocated vector object included - it will be destroyed and its memory will be reclaimed when the object goes out of scope. Trying to delete a stack-allocated object leads to undefined behavior (crash in your case).

sharptooth
  • 167,383
  • 100
  • 513
  • 979
3

First of all, faceIndicesPerVertex is not an array, so you cant call delete[].

And second, faceIndicesPerVertex is a local variable. This means it's on the stack. This means you can't use delete on it.

Only use delete on objects you allocate in the heap with new.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
2

You don't have to call delete[]. It's automatically allocated variable/container, it will be automatically destroyed/freed memory.

Call delete when you call new and vise versa. The same for new[] and delete[].

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
1

faceIndicesPerVertex is not a pointer, it was allocated on stack. You can't delete it, and you don't have to.

Igor
  • 26,650
  • 27
  • 89
  • 114
1

faceIndicesPerVertex is not a pointer, so delete[] is not required.
faceIndicesPerVertex is a vector so delete[] will not even work.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Dennis
  • 780
  • 6
  • 17
1

As far as I know, delete is used only for deallocating memory from the heap. You cannot delete stack allocated memory using delete. As a general rule, delete memory only if you dynamically allocated it using new. I also had some problems with the usage of new/delete. If you follow the general rule of using new and delete in pairs, you should be fine.

devjeetroy
  • 1,855
  • 6
  • 26
  • 43