Re: Problem with passing dynamic arrays by reference

thomas.christmann_at_online.de
Date: 08/31/04


Date: 31 Aug 2004 04:15:52 -0700


> <malloc.h> is a non-standard header and not needed in your entire
> program. Use <stdlib.h> instead.

*sic*

> This is dangerous. If realloc() fails to allocate more memory, it
> keeps the original memory intact but returns NULL. You then end up
> overwriting your previous pointer with NULL, which means both that
> you've lost touch with your memory and the next line will cause
> undefined behaviour.
> Try this instead:
> DWORD *arr, *tmp;
> arr = malloc(sizeof(DWORD));
> tmp = realloc(arr,2*sizeof(DWORD));
> if (tmp != NULL) {
> arr = tmp;
> }

I know, I know, i just skipped it for brevity. But thanks for pointing
it out (again).

> The same comments as above apply here.
> I note with interest that you appear to have got the
pointer-to-pointer
> passing in the function right. This may surprise you, but many
newbies
> get it wrong on the first try, thinking that assigning to a parameter
> changes the value of the original variable, as long as that
parameter's
> type is a pointer. You, however, are correctly assigning to what the
> pointer parameter points to.

Uhm, thanks, I guess. Newbie, hmm...

> I'm not too sharp on the C parsing rules, but I have a sneaky
> suspicion that this is parsed as *(arr[1]) = 2, which will quite
> obviously fail. Most likely if I'm wrong, Dan Pop will now tell me
> to engage my brain and actually learn C. Just to be on the safe
> side, try (*arr)[1] = 2.

Why that sneaky ***! You're right, the compiler interpreted it
wrong.
I really have to switch to some empathic compiler, that correctly
guesses
what I try to tell it ;-)

Thanks for the quick help,

Thomas