I am currently implementing a basic garbage collector which purpose it is to delete all left dynamically allocated objects at the end of program. I hope the class documentation makes it more clear:
/**
* This basic garbage collector provides easy memory leak prevention.
* Just derive your class from utils::Object and the collector will
* care about freeing dynamically allocated objects. This basic
* implementation will just free all internal cached objects at the end
* of program. So allocated memory which was not freed manually will
* stay blocked up to this point.
*/
class GarbageCollector {
private:
// All object collector should care about (true means array)
std::map< Object*, bool > objects;
GarbageCollector();
/**
* Free left allocated memory.
*/
~GarbageCollector() {
std::map< Object*, bool >::iterator it = objects.begin();
int counter = 0;
while( it != objects.end() ) {
// save pointer and iterate to next because
// delete will remove obj from object set
Object* obj = it->first;
bool array = it->second;
++it;
++counter;
if( array ) {
delete[] obj;
}
else
delete obj;
}
if( counter )
std::cout << "GC: " << counter << " object(s) freed\n";
}
public:
/**
* #return Static collector instance.
*/
static GarbageCollector& getCollector();
void addObject( Object* obj );
void addArray( Object* obj );
void remove( Object* obj );
};
This base class Object from which other classes will inherit from will add the pointer of the allocated memory to this gc:
class Object {
public:
void* operator new( std::size_t size ) {
void* ptr = malloc( size );
if( !ptr )
throw std::bad_alloc();
GarbageCollector::getCollector().addObject( static_cast<Object*>(ptr) );
return ptr;
}
void operator delete( void* ptr ) {
GarbageCollector::getCollector().remove( static_cast<Object*>(ptr) );
free( ptr );
}
void* operator new[]( std::size_t size ) {
void* ptr = malloc( size );
if( !ptr )
throw std::bad_alloc();
GarbageCollector::getCollector().addArray( static_cast<Object*>(ptr) );
return ptr;
}
void operator delete[]( void* ptr ) {
GarbageCollector::getCollector().remove( static_cast<Object*>(ptr) );
free( ptr );
}
};
This works fine for the new statement. But if try to allocate an array via new[] the program crashes. Valgrind --leak-check=yes gives this output:
==3030== Invalid read of size 8
==3030== at 0x408305: utils::GarbageCollector::~GarbageCollector() (garbageCollector.cpp:40)
==3030== by 0x55A4820: __run_exit_handlers (exit.c:78)
==3030== by 0x55A48A4: exit (exit.c:100)
==3030== by 0x558A313: (below main) (libc-start.c:258)
==3030== Address 0x5b8e038 is 8 bytes before a block of size 144 alloc'd
==3030== at 0x4C28F9F: malloc (vg_replace_malloc.c:236)
==3030== by 0x409A59: utils::Object::operator new[](unsigned long) (object.cpp:45)
==3030== by 0x409B58: start() (main.cpp:49)
==3030== by 0x409C30: main (main.cpp:54)
==3030==
==3030== Invalid free() / delete / delete[]
==3030== at 0x4C282E0: free (vg_replace_malloc.c:366)
==3030== by 0x409AE8: utils::Object::operator delete[](void*) (object.cpp:54)
==3030== by 0x408339: utils::GarbageCollector::~GarbageCollector() (garbageCollector.cpp:40)
==3030== by 0x55A4820: __run_exit_handlers (exit.c:78)
==3030== by 0x55A48A4: exit (exit.c:100)
==3030== by 0x558A313: (below main) (libc-start.c:258)
==3030== Address 0x5b8e038 is 8 bytes before a block of size 144 alloc'd
==3030== at 0x4C28F9F: malloc (vg_replace_malloc.c:236)
==3030== by 0x409A59: utils::Object::operator new[](unsigned long) (object.cpp:45)
==3030== by 0x409B58: start() (main.cpp:49)
==3030== by 0x409C30: main (main.cpp:54)
==3030==
GC: 1 object(s) freed
==3030==
==3030== HEAP SUMMARY:
==3030== in use at exit: 144 bytes in 1 blocks
==3030== total heap usage: 8 allocs, 8 frees, 896 bytes allocated
==3030==
==3030== 144 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3030== at 0x4C28F9F: malloc (vg_replace_malloc.c:236)
==3030== by 0x409A59: utils::Object::operator new[](unsigned long) (object.cpp:45)
==3030== by 0x409B58: start() (main.cpp:49)
==3030== by 0x409C30: main (main.cpp:54)
==3030==
==3030== LEAK SUMMARY:
==3030== definitely lost: 144 bytes in 1 blocks
==3030== indirectly lost: 0 bytes in 0 blocks
==3030== possibly lost: 0 bytes in 0 blocks
==3030== still reachable: 0 bytes in 0 blocks
==3030== suppressed: 0 bytes in 0 blocks
==3030==
==3030== For counts of detected and suppressed errors, rerun with: -v
==3030== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 4 from 4)
I debugged the program an the gc is trying to delete the memory at the adress which new[] returned. Can you tell me where my fault is?
You cannot use delete[] expression with a pointer returned from operator new[]. You must use operator delete[] directly.
This is because new[] expression sometimes adjusts the result of operator new[], and delete[] expression adjusts the argument in the opposite direction So:
If you have a pointer returned by a new[] expression, free it with a delete[] expression.
If you have a pointer returned by a call to operator new[], free it with a call to operator delete[].
In general, this is also true with respect to new expression/operator new/delete expression/operator delete, but GCC lets you get away with this.
This is a technical answer, concerning only the crash. The usefulness of the code as a memory leak prevention tool is discussed in comments.
Update A quick an dirty example of the thesis can be found at http://ideone.com/0atp5
Please note that if you call operator delete[] instead of delete[],
The destructors will not be called (but if you free all objects automatically, destructors are not needed anyway)
You do not need to cast pointers to Object* and back, just store everything as a void*.
GarbageCollector::~GarbageCollector() calls Object::operator[] delete and Object::operator delete, which change the GarbageCollector::objects map, while iterating over it. Try making a copy first:
...
std::map< Object*, bool > objectsCopy = objects;
std::map< Object*, bool >::iterator it = objectsCopy.begin();
int counter = 0;
while( it != objectsCopy.end() ) {
...
If you do this only at the end of the program, inhibit the remove() calls to not remove it at all. This object will be destroyed an instant later and the map will be empty regardless.
Related
I wrote a small piece of code like this:
template <class T>
void
test()
{
T* ptr = nullptr;
ptr = (T*)malloc(1 * sizeof(T));
new ((void*)ptr) T(T());
ptr = (T*)realloc(ptr, 2 * sizeof(T));
new ((void*)(ptr + 1)) T(T());
(ptr)->~T();
(ptr + 1)->~T();
free(ptr);
}
struct foo
{
foo() : ptr(malloc(10)) {}
~foo() { free(ptr); }
void* ptr;
};
int
main()
{
test<int>(); // this is ok
test<foo>(); // this is ok
test<std::string>(); // memory error :(
return 0;
};
When T is [int] or [foo], everything works fine. But using [std::string] as T causes valgrind to report memory errors like this:
==18184== Memcheck, a memory error detector
==18184== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==18184== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==18184== Command: ./a.out
==18184==
==18184== Invalid free() / delete / delete[] / realloc()
==18184== at 0x4C2C20A: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18184== by 0x401074: void test<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >() (tmp.cpp:26)
==18184== by 0x400CFC: main (tmp.cpp:44)
==18184== Address 0x5a89e70 is 16 bytes inside a block of size 32 free'd
==18184== at 0x4C2CC37: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18184== by 0x401042: void test<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >() (tmp.cpp:22)
==18184== by 0x400CFC: main (tmp.cpp:44)
==18184== Block was alloc'd at
==18184== at 0x4C2AB8D: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18184== by 0x40100F: void test<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >() (tmp.cpp:18)
==18184== by 0x400CFC: main (tmp.cpp:44)
==18184==
==18184==
==18184== HEAP SUMMARY:
==18184== in use at exit: 0 bytes in 0 blocks
==18184== total heap usage: 9 allocs, 10 frees, 72,856 bytes allocated
==18184==
==18184== All heap blocks were freed -- no leaks are possible
==18184==
==18184== For counts of detected and suppressed errors, rerun with: -v
==18184== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
why only [std::string] leads to memory problem while [foo] also has malloc/free in both ctor & dtor ?
I'm using g++ 6.2.1 and valgrind 3.12.0
malloc(), free(), and realloc() are C library functions, that know absolutely nothing about C++ classes, their constructors, and destructors.
You are using malloc() with placement new to construct a std::string using malloc-ed memory. This is fine.
But then, you're using realloc() to reallocate the allocated memory.
Copying/moving C++ objects in memory must be done using the respective objects' copy/move constructors. Copying/moving C++ objects in memory cannot be done with realloc().
The only way to do this is to malloc() a new memory block, use placement new to invoke the objects' copy/move constructors in order to copy/move them into the new memory block, and finally invoke the destructor of the objects in the old memory block, after which it can be free()-ed.
realloc is not compatible with non-POD types.
Because it can move things in memory without the moved objects being aware of it.
I found this memory leak from Valgrind which gave the memory error: Invalid free() / delete / delete[] / realloc().
==7367== Invalid free() / delete / delete[] / realloc()
==7367== at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7367== by 0x40077F: ItemSet::~ItemSet() (cart.cpp:33)
==7367== by 0x40086B: ShoppingCart::~ShoppingCart() (cart.cpp:14)
==7367== by 0x400828: main (cart.cpp:45)
==7367== Address 0x5a1c0b0 is 0 bytes inside a block of size 40 free'd
==7367== at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7367== by 0x40077F: ItemSet::~ItemSet() (cart.cpp:33)
==7367== by 0x400800: ShoppingCart::ShoppingCart() (cart.cpp:39)
==7367== by 0x400817: main (cart.cpp:43)
==7367==
==7367==
==7367== HEAP SUMMARY:
==7367== in use at exit: 40 bytes in 1 blocks
==7367== total heap usage: 2 allocs, 2 frees, 80 bytes allocated
==7367==
==7367== LEAK SUMMARY:
==7367== definitely lost: 40 bytes in 1 blocks
==7367== indirectly lost: 0 bytes in 0 blocks
==7367== possibly lost: 0 bytes in 0 blocks
==7367== still reachable: 0 bytes in 0 blocks
==7367== suppressed: 0 bytes in 0 blocks
==7367== Rerun with --leak-check=full to see details of leaked memory
==7367==
==7367== For counts of detected and suppressed errors, rerun with: -v
==7367== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Here is the code. Its a simplified version of my program, but it still has the problem I am having.
#include <cstdlib>
class ItemSet {
private:
int* items;
public:
ItemSet();
virtual ~ItemSet();
// ItemSet Methods...
};
class ShoppingCart {
private:
ItemSet items_in_cart;
public:
ShoppingCart();
// ShoppingCart methods...
};
ItemSet::ItemSet() {
// Constructor
int max_num_of_items = 10;
items = (int*)calloc(sizeof(int), max_num_of_items);
}
ItemSet::~ItemSet() {
// Destructor
if (NULL != items) {
// Frees the dynamically allocated register files
free(items);
}
}
ShoppingCart::ShoppingCart() {
// Constructor
items_in_cart = ItemSet();
}
int main() {
ShoppingCart cart = ShoppingCart();
return 0;
}
ShoppingCart::ShoppingCart() {
// Constructor
items_in_cart = ItemSet();
}
That last line can't possibly work. Right after the assignment, we have two ItemSet objects with the same value for items -- the temporary created on the right side and items_in_cart. When the second one is destroyed, you have a double free.
Use a sensible method of having a collection of objects like std::list, std::vector, or std::array. Otherwise, follow the rule of 3, rule of 5, or of zero.
I am a beginner of C++, and still very confused if I correctly freed memories and removed possible dangling pointers. It was one of my school assignments in the past. There were so many students have the same problems, and no one else could help me.
Please identify where I have problems.
==25334== Mismatched free() / delete / delete []
==25334== at 0x4006D21: free (vg_replace_malloc.c:446)
==25334== by 0x80492F2: HashTable::~HashTable() (Hash.c:115)
==25334== by 0x8049145: SymTab::~SymTab() (SymTab.h:9)
==25334== by 0x8048E9D: main (Driver.c:170)
==25334== Address 0x402c0b8 is 0 bytes inside a block of size 12 alloc'd
==25334== at 0x4007862: operator new(unsigned int) (vg_replace_malloc.c:292)
==25334== by 0x8048C73: main (Driver.c:143)
==25334==
==25334==
==25334== HEAP SUMMARY:
==25334== in use at exit: 18 bytes in 4 blocks
==25334== total heap usage: 10 allocs, 6 frees, 106 bytes allocated
==25334==
==25334== 18 bytes in 4 blocks are definitely lost in loss record 1 of 1
==25334== at 0x4007D58: malloc (vg_replace_malloc.c:270)
==25334== by 0x97E96F: strdup (strdup.c:43)
==25334== by 0x8048FDC: UCSDStudent::UCSDStudent(char*, long) (Driver.c:36)
==25334== by 0x8048C92: main (Driver.c:143)
==25334==
==25334== LEAK SUMMARY:
==25334== definitely lost: 18 bytes in 4 blocks
==25334== indirectly lost: 0 bytes in 0 blocks
==25334== possibly lost: 0 bytes in 0 blocks
==25334== still reachable: 0 bytes in 0 blocks
==25334== suppressed: 0 bytes in 0 blocks
==25334==
==25334== For counts of detected and suppressed errors, rerun with: -v
==25334== ERROR SUMMARY: 5 errors from 2 contexts (suppressed: 15 from 8)
Base.h
#ifndef BASE_H
#define BASE_H
#include <iostream>
using namespace std; /* C error */
/* TEMPLATE */
struct Base { /* C++ struct is public class, public methods */
/* PUBLIC SECTION */
/* virtual: candidates for redefinition */
virtual operator char * (void) {
return 0;
}
virtual operator long (void) { // hash function
return 0;
}
virtual long operator == (Base & base) {// isequal function
return *this == base;
}
Base (void) {} // new_element
virtual ~Base (void) {} // delete_element
virtual ostream & Write (ostream & stream) = 0;// write_element
};
#endif
Driver.c
class UCSDStudent : public Base { /* extends Base */
char * name;
long studentnum;
public:
UCSDStudent (char * nm, long sn) :
name (strdup (nm)), studentnum (sn) {} /* Initialization */
~UCSDStudent (void) { /* Destructor */
free (name);
}
Hash.c
/* HashTable constructor */
HashTable :: HashTable (int sz) : size (sz),
table_count(++counter), occupancy (0), table (new Base *[sz]),
probeCount (new int[sz])
HashTable :: ~HashTable (void)
{
/* call function to delete individual elements */
for(int index2 = 0; index2 < size; index2++)
{
if(table[index2] != NULL)
{
free(table[index2]);
table[index2] = NULL;
}
delete table[index2];
}
/*
* delete table itself
* Freed memory
*/
delete[] table;
delete[] probeCount;
/* pointed dangling ptr to NULL */
table = NULL;
probeCount = NULL;
} /* end: ~HashTable */
The two Valgrind errors ("Mismatched free() / delete / delete []" and "18 bytes in 4 blocks are definitely lost") might be related.
In ~HashTable() you call free(table[index2]) which probably means to destroy the UCSDStudent objects (not sure, as you didn't post the whole program, esp. not the code which insert elements into HashTable). I suppose you create UCSDStudent objects with new - and in that case, you also have to use the corresponding destruction method (in this case delete instead of free()). This is the cause for the first Valgrind error.
Furthermore, the free() function will not call the object's destructor, while delete will do that. This would explain why ~UCSDStudent() is not called, causing your program to leak the memory for the student name. So using delete instead of free() in ~HashTable() should solve both errors.
In general, you should try to stay with one way of memory allocation (either malloc()/free() or new/new[]/delete/delete[]). And given that this is a C++ program, new would be the appropriate choice. In the same vein, I'd advise you to remove the strdup() and char* stuff and switch to std::string instead - this would remove another location where you might mix up free() and delete.
You're calling free on memory that appears to have been declared using new, which is the main error coming out of Valgrind there. You also appear to not be following the Rule of Three (although that doesn't appear to be your entire code there).
I would highly recommend you switch to using smart pointers such as std::shared_ptr / std::unique_ptr, and use std::vector / std::array to create containers.
Looks to me like you never call ~UCSDStudent. Unfortunately, it's not possible to tell from the code you have posted, but the destructor itself looks good, so I expect the problem is that the destructor isn't being called.
See the program below:
#include <cstdio>
#include <cstring>
#include <iostream>
class Chaine {
private:
char* _donnees;
unsigned int _taille;
public:
Chaine();
Chaine(const char*);
~Chaine();
unsigned int taille() const;
};
Chaine::Chaine():_taille(0) {
_donnees=new char[1];
_donnees[0]='\0';
}
Chaine::Chaine(const char *s) {
_taille = std::strlen(s);
_donnees = new char[_taille + 1];
std::strcpy(_donnees, s);
std::printf("%s(%d): %s\n", __FILE__, __LINE__, __func__);
}
Chaine::~Chaine() {
if(*_donnees == 0){
std::printf("_donnees points to freed block\n");
}
else{
std::printf("_donnees points to freed block\n");
delete[] _donnees;
_donnees=NULL;
}
std::printf("%s(%d): %s\n", __FILE__, __LINE__, __func__);
}
unsigned int Chaine::taille() const{
return _taille;
}
int main() {
Chaine s1("une chaine");
Chaine *s2 = new Chaine("s3");
Chaine s3 = s1;
delete s2;
}
I compiled using g++ -Wall -o test test.cpp then run valgrind --leak-check=full ./test and got messages below:
/test
==5638== Memcheck, a memory error detector
==5638== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==5638== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==5638== Command: ./test
==5638==
test.cpp(29): Chaine
test.cpp(29): Chaine
_donnees points to freed block
test.cpp(41): ~Chaine
_donnees points to freed block
test.cpp(41): ~Chaine
==5638== Invalid read of size 1
==5638== at 0x804886D: Chaine::~Chaine() (in /home/qliang/Documents/ENSEIRB/cpp/td2/chaine2/test)
==5638== by 0x804895F: main (in /home/qliang/Documents/ENSEIRB/cpp/td2/chaine2/test)
==5638== Address 0x4353028 is 0 bytes inside a block of size 11 free'd
==5638== at 0x402B598: operator delete[](void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==5638== by 0x80488A3: Chaine::~Chaine() (in /home/qliang/Documents/ENSEIRB/cpp/td2/chaine2/test)
==5638== by 0x8048953: main (in /home/qliang/Documents/ENSEIRB/cpp/td2/chaine2/test)
==5638==
_donnees points to freed block
==5638== Invalid free() / delete / delete[] / realloc()
==5638== at 0x402B598: operator delete[](void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==5638== by 0x80488A3: Chaine::~Chaine() (in /home/qliang/Documents/ENSEIRB/cpp/td2/chaine2/test)
==5638== by 0x804895F: main (in /home/qliang/Documents/ENSEIRB/cpp/td2/chaine2/test)
==5638== Address 0x4353028 is 0 bytes inside a block of size 11 free'd
==5638== at 0x402B598: operator delete[](void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==5638== by 0x80488A3: Chaine::~Chaine() (in /home/qliang/Documents/ENSEIRB/cpp/td2/chaine2/test)
==5638== by 0x8048953: main (in /home/qliang/Documents/ENSEIRB/cpp/td2/chaine2/test)
==5638==
test.cpp(41): ~Chaine
==5638==
==5638== HEAP SUMMARY:
==5638== in use at exit: 0 bytes in 0 blocks
==5638== total heap usage: 3 allocs, 4 frees, 22 bytes allocated
==5638==
==5638== All heap blocks were freed -- no leaks are possible
==5638==
==5638== For counts of detected and suppressed errors, rerun with: -v
==5638== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
I the deconstructor, I want to check if the memory _donnees points to has been freed to avoid re-free.
One solution(maybe bad solution) is to declare a static integer in deconstructor, like
Chaine::~Chaine() {
static int num_free = 0;
if(num_free == 1){
std::printf("_donnees points to freed block\n");
}
else{
std::printf("_donnees points to freed block\n");
delete[] _donnees;
num_free = 1;
_donnees=NULL;
}
std::printf("%s(%d): %s\n", __FILE__, __LINE__, __func__);
}
But I want to know if there is some way like *_donnees == NULL to check if the block of memory is freed or not.
And, why valgrind displays messages:
==5638== Invalid read of size 1
==5638== Invalid free() / delete / delete[] / realloc()
and why each of these messages just show once?
You are violating the Rule of Three. You should define a copy constructor and a copy assignment operator.
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.
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.
If this is the SECOND (or later) time you call resize, then this is a very likely scenario, because you are trying to delete on a heap that has already had a double delete since the temp was already deleted, and now all your objArray writes have gone into a lump of memory that belongs to the heap-management, not to your code.
All sorts of other potential issues may also happen here, such as the memory is now being used for some OTHER object, and it's writing things into the heap memory that you then use as objArray.
You shouldn't delete temp where you are trying to do so. Just don't.
Explicit delete (or delete[]) should only be needed in very low-level library code. Everywhere else you should use smart pointers instead.
Here's a better approach that is (IMO) easier to understand:
std::unique_ptr<Obj[]> temp(new Obj[size * 2]);
// copy stuff from objarray to temp
swap(objarray, temp);
That's it. The unique_ptr destructor will free the old objarray buffer if the swap succeeded. And if an exception was thrown during the copy, it will free the new temporary buffer. In either case objarray (which should also be std::unique_ptr<Obj[]>) is left with a valid buffer.