Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array and malloc woes...

Status
Not open for further replies.

DoraC

Programmer
May 7, 2002
98
US
Hi,

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(&quot; string is: .%s.\n&quot;, 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(&quot; string is: .%s.\n&quot;, 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


 
Allocating and freeing memory at runtime is where
a lot of C programming errors occur. One off errors,
freeing unallocated memory, allocating memory for
multidimensional arrays illegally, and memory leaks
are all common mistakes, and are easy to commit.

Remember that when you allocate memory for a multi-
dimensional array, depending on how you do it, for
each &quot;row&quot; you create you need to allocate memory.

An overall approach to dynamic allocation could look
like this:
Code:
#define ISZ 5
#define blen 100

char **initArray(char **name, int sz) {
int p;
char **new;

     if (name == NULL) {
          new = malloc(ISZ * sizeof(char *));
          for (p=0 ; p < ISZ ; p++) {
              new[p] = malloc(blen * sizeof(char));
          }
          return new;
     } else {
         new = malloc((sz + ISZ) * sizeof(char *));
              for (p=0 ; p < sz ; p++) {
                  new[p] = malloc(strlen(name[p]) + 1 * sizeof(char));
                  strcpy(new[p],name[p]);
                  printf(&quot;Copied from src: %s to dst: %s\n&quot;,name[p],new[p]);
                  free(name[p]);
               }

              for (p=sz ; p < (sz + ISZ) ; p++)  {
                 new[p] = malloc(blen * sizeof(char));
              }

           free(name);
           return new;
      }
return NULL;
}

In freeing the memory allocated an easy approach is
something like this:
Code:
void freeArray(char **arr, int sz) {
int p = 0;

           while (p < sz) {
                 free(arr[p]);
                 p++;
           }
free(arr);
}


An example of use:
Code:
int main(int argc, char **argv) {
int y = 0, prev = ISZ, x;
char **storage, **tmp;

          storage = dynArray(NULL,0);

            if (storage) {
                while (y < 10) {
                       if (y == prev) {
                          tmp = dynArray(storage,y);
                          storage = tmp;
                          prev += ISZ;
                       }
                      printf(&quot;Enter a string: &quot;);
                      fgets(storage[y],blen,stdin);
                      y++;
                 }
            } else {
               printf(&quot;Failed to malloc() in main()\n&quot;);
               return 1;
            }

freeArray(storage,y);
return 0;
}

HTH
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top