Search code examples
c++pointersdelete-operator

Can't delete temporary object


I'm resizing and array of objects. I made a temp object but when I don't delete it Valgrind shows memory leaks and an error. Deleting it causes a segfault. Just wondering what Valgrind is complaining about...

void Obj::resize()
{
  Obj *temp = new Obj[size * 2];   //<-- line 92
  for (int i = 0; i < size; i++)
    temp[i] = objarray[i];
  delete [] objarray;
  objarray = temp;
  size *= 2;
  //delete temp;   //<-- causes segfault
  //delete [] temp;  // also segfaults, tried them both just in case :\
}

Here's the Valgrind report:

==9292== HEAP SUMMARY:
==9292==     in use at exit: 21,484 bytes in 799 blocks
==9292==   total heap usage: 3,528 allocs, 2,729 frees, 91,789 bytes allocated
==9292==
==9292== 21,484 (2,644 direct, 18,840 indirect) bytes in 1 blocks are definitely lost in loss record 4 of 4
==9292==    at 0x4008409: operator new[](unsigned int) (vg_replace_malloc.c:357)
==9292==    by 0x804AC7E: MyClass::resize() (file.cpp:92)
==9292==    by 0x804AC34: MyClass::add(int, int) (file.cpp:82)
==9292==    by 0x804AAE6: getline(std::istream&, MyClass&) (file.cpp:66)
==9292==    by 0x8049772: main (otherfile.cpp:39)
==9292==
==9292== LEAK SUMMARY:
==9292==    definitely lost: 2,644 bytes in 1 blocks
==9292==    indirectly lost: 18,840 bytes in 798 blocks
==9292==      possibly lost: 0 bytes in 0 blocks
==9292==    still reachable: 0 bytes in 0 blocks
==9292==         suppressed: 0 bytes in 0 blocks
==9292==
==9292== For counts of detected and suppressed errors, rerun with: -v
==9292== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

I'm not too good with gdb, but got this backtrace:

    (gdb) run
Starting program: 

Program received signal SIGSEGV, Segmentation fault.
0x46ed40e3 in free () from /lib/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.15-58.fc17.i686 libgcc-4.7.2-2.fc17.i686 libstdc++-4.7.2-2.fc17.i686
(gdb) backtrace
#0  0x46ed40e3 in free () from /lib/libc.so.6
#1  0x4742dba0 in operator delete(void*) () from /lib/libstdc++.so.6
#2  0x0804ad68 in MyClass::resize (this=0xbffff28c) at file.cpp:98
#3  0x0804ac35 in MyClass::add (this=0xbffff28c, month=10, day=31)
    at file.cpp:82
#4  0x0804aae7 in getline (input=..., a=...) at file.cpp:66
#5  0x08049773 in main (argc=1, argv=0xbffff344) at otherfile.cpp:39
(gdb)

I think that deleting this is bad, because it should just leave the pointer dangling, so it doesn't surprise me that I get a segfault. Still, why would it then cause memory problems? Any ideas would be greatly appreciated.


Solution

  • Indeed, you can't delete it there since you've assigned it to objarray to be used later.

    Most likely, you're not deleting objarray in the destructor; or some other function is reassigning it without deleting the old array first.

    I would use std::vector rather than a hand-crafted array, to take care of deallocation for me.