lchristina26
lchristina26

Reputation: 205

C Program: Update unsigned char pointer array with function

I have a function to update an unsigned char* and cannot find where my bug is. I'm not sure if I need to allocate memory, or if I am pointing to the wrong memory space somewhere. I tried to follow a similar structure as posted here, but have not had success with an unsigned char.

My code so far:

#include <stdio.h>

void changeArray(unsigned char **arr)
{
    unsigned char ptr[3] = {100, 101, 102};
    *arr = ptr;
    printf("%d\n", **(arr+0)); // This prints out the correct value of 100
}

int main(int argc, const char* argv[])
{
    int i = 0;
    unsigned char *blah;
    unsigned char ptr2[3] = {103, 104, 105};
    blah = ptr2;
    printf("Blah is: \n");
    for (i = 0; i < 3; i++) {
        printf("%d,",*(blah+i)); //This prints out 103,104,105
    }
    changeArray(&blah);
    printf("Blah is now: \n");
    for (i = 0; i < 3; i++) {
        printf("%d,", *(blah +i)); //This prints out 0,0,0
    }
    return 0;
}

Any help in determining how to properly access the values set in the changeArray() function would be greatly appreciated.

Upvotes: 1

Views: 2962

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

The problem here is, ptr is local to changeArray() function. So once the function finishes execution, there is no existance of ptr. Hence, once you assign ptr to *arr

*arr = ptr;

and changeArray() execution gets over, accessing blah in main() now will invoke undefined behaviour.

FWIW, you don't need to pass the address of blah, you don't need a pointer-to-pointer at all. blah is already a pointer, which you can pass to changeArray() to alter the contents of the memory area it points to. You can do something like

void changeArray(unsigned char *arr)
{
     for (int i = 0; i < 3; i ++)
        arr[i] = 100+i;
}

and call it like

changeArray(blah);

Upvotes: 1

P.P
P.P

Reputation: 121397

With this *arr = ptr; you are storing a pointer to a variable with automatic storage duration. The behaviour undefined.

You can dynamically allocate and return a pointer that way:

void changeArray(unsigned char **arr)
{
    unsigned char ptr[3] = {100, 101, 102};
    unsigned char *p = malloc(sizeof ptr); 
    memcpy(p, ptr, sizeof ptr);
    *arr = p;
    printf("%d\n", **(arr+0)); // This prints out the correct value of 100
}

You should also do error checking if malloc failed and remember to free the allocated memory after use in main.

Upvotes: 2

Related Questions