Hello fellow linux developers. I seem to be having some serious problems
with the dynamic memory allocation routines in C++. I am using a pretty
vanilla Slackware 2.0.0- libc 4.5.26, gcc 2.5.8, kernel 1.1.54/62.
What I am trying to do is create a dynamically sized list of char
pointers. When adding one, the old char ** array is reallocated and
the old contents are copied into it. The routine that accomplishes
this is add_stringlist(), below. Another routine involved is clear(),
also below, which deallocates the list once and for all. However,
when the "delete" statement is called, the program crashes with a
segmentation fault. Not on the first time, mind you- it takes a few tries
before it happens- but generally less than ten. I've tried both
"delete" and "delete []." (The function newdup does a strdup but
allocates the memory with new.)
I am completely stumped. Would anyone have any help for me? This was
happening yesterday with another deallocation of a char ** that I was
trying to do as well- I eventually just stopped deallocating it due to
frustration.
A trace from GDB follows, as well as the two code fragments. I appreciate
all responses.
Cheers,
Doug
A trace from GDB 4.12 reveals:
(gdb) where
#0 0x14521 in _free_internal (ptr=0x2000) at free.c:169
#1 0x14602 in free (ptr=0x2000) at free.c:217
#2 0xfe30 in __builtin_delete (ptr=0x2000)
toadd=0x2c300 "somestring") at somefile.C:103
...
(gdb) list
98 int i;
99
100 newlist = new char *[count + 1];
101 for (i = 0; i < count; i++)
102 newlist[i] = list[i];
103 delete [] list;
104 list = newlist;
105 list[count++] = newdup(toadd);
106 }
107
void add_stringlist(int &count, char ** &list, const char *toadd)
{
char **newlist;
int i;
newlist = new char *[count + 1];
for (i = 0; i < count; i++)
newlist[i] = list[i];
delete [] list;
list = newlist;
list[count++] = newdup(toadd);
void some_class::clear(void)Quote:}
// Frees all allocated memory
{
int i;
# define CINN(x) do { if ((x)) { delete (x); (x) = NULL; } } while (0)
// clear if not null
for (i = 0; i < msgcount; i++)
CINN(messages[i]);
delete [] messages; // This is causing core dump???
msgcount = 0;
...
# undef CINN
Quote:}