0

I have the following function (in C)

void initArr (int ** arr, int size, int value) {
* arr = (int*)malloc(size * sizeof(int));
if (*arr!=NULL) {
        for (int i = 0; i<size;i++) {
            *(*arr + i) = value;
        }
    }
}

which I call in main:

int main(void) {
    int *myArr = NULL;
    initArr(&myArr,10,45);
    for (int i = 0; i<15; i++) {
        printf("myArr[%d] = %d\n", i, *myArr);
    }
    return 0;
}

and the output is:

myArr[0] = 45
myArr[1] = 45
myArr[2] = 45
myArr[3] = 45
myArr[4] = 45
myArr[5] = 45
myArr[6] = 45
myArr[7] = 45
myArr[8] = 45
myArr[9] = 45
myArr[10] = 45
myArr[11] = 45
myArr[12] = 45
myArr[13] = 45
myArr[14] = 45

What I don't understand is that I've explicitly assigned only the first 10 elements of the array to the given value. However when I print past the 10th element, I see that the value is also assigned to those. Why is that?

  • 3
    `*myArr` ==> `myArr[i]` in your `printf` expression. All your loop does is repeated print the first element. Unrelated, break the habit of casting `malloc` in C programs; [it is neither necessary nor advised](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – WhozCraig Oct 03 '20 at 09:02
  • Thank you friend! Can't believe I missed that... and thanks for the tip on casting, I had no idea – Axel Brugger Oct 03 '20 at 09:11
  • regarding; `*(*arr + i) = value;` much better to write: `arr[i] = value;` – user3629249 Oct 05 '20 at 14:48

1 Answers1

1

2 things to note, as mentioned in the comments you are dereferencing only the pointer to the first element. you can fix it by for (int i = 0; i<15; i++, myArr++) or printf("myArr[%d] = %d\n", i, myArr[i]); now that we got that out of the way, it is undefined behaviour to try and reach memory that doesn't 'belong' to you. you've allocated only 10 * sizeof(int) bytes for your pointer, so you should write only to that memory, and you should only read out of that memory. you shouldn't rely on the results of what happens in your code, it is bad practice and can lead to bad code.

Gilad
  • 305
  • 1
  • 2
  • 8