user1357576
user1357576

Reputation: 409

Why does the pointer address return to 0 despite allocation on heap?

Here is the programming snippet

void func1 (UInt8* data, size_t length)
{

       UInt8 *data2;

        //do some actions to populate data2 with valid data;

       length = 12;
       data = malloc(length);
       memset(data, 0 , length);
       memcpy(&data[0], &data2[9] , length);

      return;
}


void main()
{
     void *data;
     size_t dataSize;

     func1 (data, dataSize)

     printf ("%s", data);
}

The problem here is that when I see the address of the data in the debugger after it returns from the func1 it points to 0x0000. My understanding is that since data was allocated on the heap, it should continue to point to whatever address it was pointing to in the function.

What am I missing here?

Upvotes: 0

Views: 89

Answers (3)

StarkOverflow
StarkOverflow

Reputation: 39

In fact, when you pass the data as a pointer to the function, you can only modify the value under the pointer, not the pointer itself.

To do that, you have to use double pointers, like that:

void fillData(UInt8** data, size_t length)
{
    UInt8 *data2;
    // fill data2

    *data = malloc(length);
    memset(*data, 0 , length);
    memcpy(data[0], &data2[9], length);
}    

int main()
{
    void *data;
    unsigned int dataSize = 42;
    fillData(&data, dataSize):

    printf("%s", data);
    return 0;
}

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564403

The data still exists on the heap, but the pointer you passed into func1 will not change at the call site, so you're "leaking" the memory.

You need to pass a pointer to a pointer, to be able to handle this:

func1(&data, &dataSize);

void func1 (UInt8** data, size_t *length)
{

   UInt8 *data2;

    //do some actions to populate data2 with valid data;

   length = 12;
   *data = malloc(*length);
   memset(*data, 0 , *length);
   memcpy(*data, &data2[0] , *length);

   return;
}

Upvotes: 2

anotherdev
anotherdev

Reputation: 2569

Correction:

void func1 (UInt8** data, size_t length)
{

       UInt8 *data2;

        //do some actions to populate data2 with valid data;

       length = 12;
       *data = malloc(length);
       memset(*data, 0 , length);
       memcpy(data[0], &data2[9] , length);

      return;
}

When you call a function, its parameters are copied. To modify the pointer out of the function, without using function return value, you have to use a pointer to modify your pointer.

Upvotes: 0

Related Questions