Eric said:
I think this is correct but i wanted to be sure, I'm wanting someone to tell
me if I'm doing the array allocation and deallocation correctly.
int i, wc = 0;
char *vptr;
char **Array;
Array = malloc(sizeof(char **));
This is probably wrong. You're assigning to Array, (which is a object
of type pointer to pointer to char), sizeof(char **) bytes. This would
make Array point to the start of a region of memory large enough to
hold on variable of type char **, which is what Array already is.
Furthermore if you change the type of Array in the future, then the
value returned by the sizeof will not be correct. You've also failed to
check weather malloc() has succeeded or not.
In fact given rest of your code, I don't think this statement is needed
at all.
while(some condition)
{
vptr = some char array with a length 1 and 20 bytes
Not as you've declared above. It's a pointer to type char. It won't
automatically point to anywhere. I'm assuming you've initialised it to
the start of an array in code you've not shown above.
Array = realloc(Array, sizeof(char**)*wc+1);
Many mistakes here. Firstly always pass realloc() a *copy* of the
pointer. If realloc() fails to resize the memory block, it will return
a null pointer *without* altering the original memory block, in which
case the assignment above means that you've lost access to it. Again
you've failed to check the return value of realloc(). Again hard-coding
the type of Array into the sizeof operator is inflexible. The following
form of the statement may be better:
/* Copy the return value of realloc() into a temp. pointer */
tmp_ptr = realloc(Array, sizeof **Array * wc + 1);
if(tmp_ptr)
Array = tmp_ptr;
else
free(Array);
/* Do something else */
Array[wc] = malloc(strlen(vptr)+1);
Again check for malloc() failure.
strcpy(WordArray[wc], vptr);
Are you sure this is what you want? You haven't included the
declaration of WordArray so I can't say anything definite at this
point. Always include the declaration of objects shown in the code, or
atleast mention their types.
Not quite. First make all your flight checks.