Problem with passing dynamic arrays by reference

From: Thomas Christmann (thomas.christmann_at_online.de)
Date: 08/31/04


Date: 31 Aug 2004 02:28:55 -0700

Hi!

Sorry for the weird topic, I don't know how to describe it better...
I have a little problem here I can't wrap my mind around. If I do:

-------------------------------------
#define DWORD unsigned long
#include <stdio.h>
#include <malloc.h>

int main(int argc, char* argv[])
{
        DWORD *arr;
        int i;
        
        arr = malloc(sizeof(DWORD));
        arr[0] = 1;
        arr = realloc(arr,2*sizeof(DWORD));
        arr[1] = 2;
        for(i=0;i<=1;i++)
        {
                printf("%d\n",arr[i]);
        }
}
-------------------------------------

This works just fine, as expected. But when I try to do the allocation
and assignment inside a function, I get some (to me) strange behaviour.

-------------------------------------
#define DWORD unsigned long
#include <stdio.h>
#include <malloc.h>

void func(DWORD **arr)
{
        *arr = malloc(sizeof(DWORD));
        *arr[0] = 1;
        *arr = realloc(*arr,2*sizeof(DWORD));
        // crash here, as if trying to write to a bad ptr location
        *arr[1] = 2;
}

int main(int argc, char* argv[])
{
        DWORD *arr;
        int i;
        
        func(&arr);
        for(i=0;i<=2;i++)
        {
                printf("%d\n",arr[i]);
        }
}
-------------------------------------

I'm sure it's quite easy and I just don't see it, but I just can't
figure out whats wrong with the code above. Can someone help me please?

Thanks,

Thomas

P.S.: Yes, I normally check for return values of malloc and realloc, I just
left it out of the post for brevity ;-)



Relevant Pages