Hi,
I'm having some difficulties with arrays containing malloc-ated memory... here's an example (shortened) of what I'm doing:
in the first test, everything works beautifully...
However, I get hideous Bus-error/coredumps with the second.
Specifically, calling FreeMem() seems to corrupt elements in the StringArray of index higher than i...
I'm confused - aren't they doing the same thing, freeing
memory allocated via malloc - working on what's ostensibly the same memory address? If I put a display in the
FreeMem function, it displays what I expect so it must be being passed its char* pointer appropriately.
As you can probably tell, I'm a newbie to C and I am finding this frustrating. Any help greatly appreciated!
Thanks
dora
I'm having some difficulties with arrays containing malloc-ated memory... here's an example (shortened) of what I'm doing:
Code:
struct Struct
{
char** sString;
int iCount;
};
void FreeMem( char* sInString )
{
free( sInString );
};
struct Struct LoadStruct()
{
/* in here, we create a struct with, say, n char* strings
contained in sString, and iCount set to n...
the char* strings are created with malloc, since
we only know how many to make at runtime... */
};
main( int argc, char* argv[] )
{
struct Struct StringArray = LoadStruct();
/* first test... */
for( int i = 0; i <= StringArray.iCount; i++ )
{
/* display our string... */
printf(" string is: .%s.\n", StringArray.sString[ i ]);
/* free the memory associated with it... */
free( StringArray.sString[ i ] );
};
/* second test... */
StringArray = LoadStruct();
for( int i = 0; i <= StringArray.iCount; i++ )
{
/* display our string... */
printf(" string is: .%s.\n", StringArray.sString[ i ]);
/* call function to free associated memory... */
FreeMem( StringArray.sString[ i ] );
};
};
in the first test, everything works beautifully...
However, I get hideous Bus-error/coredumps with the second.
Specifically, calling FreeMem() seems to corrupt elements in the StringArray of index higher than i...
I'm confused - aren't they doing the same thing, freeing
memory allocated via malloc - working on what's ostensibly the same memory address? If I put a display in the
FreeMem function, it displays what I expect so it must be being passed its char* pointer appropriately.
As you can probably tell, I'm a newbie to C and I am finding this frustrating. Any help greatly appreciated!
Thanks
dora