0

I have been playing around with '2D arrays' (double pointers) in c, and noticed that assigning data to memory I have not allocated works.

#include <stdio.h>
#include <stdlib.h>

int main() {
    float **arr;
    int i;
    arr = (float **) malloc(5 * sizeof(float*));
    for(int i = 0; i < 5; i++) {
        arr[i] = (float *) malloc(5 * sizeof(float));
    }
    arr[4][1000] = 6;
    printf("%f\n", arr[4][1000]);
    return 0;
}

This program successfully compiles and runs, with no segmentation fault.

However, if I were to change the reference to arr[1000][1000], it is then I get the segmentation fault.

Why does this occur?

CoopDaddio
  • 577
  • 1
  • 5
  • 20
  • *and noticed that assigning data to memory I have not allocated works.* thats.. the magic of C, i believe as long as you are on heap section of the memory, without nudging your own code, or someone else memory section it is possible. cmiiw. oh right, you can check [this answer](https://stackoverflow.com/a/27881098/4648586) for proper explanation. – Bagus Tesa Sep 09 '19 at 02:23
  • Undefined behaviour, *anything* could happen. Typically, memory is organised in pages, and as long as you access memory in the same page, the address remains valid (from OS view, not programme view!). Typically, in front of an array usually resides some control block containing data necessary for de-allocation. You might try the same with a one-dimensional array writing at `array[-1]`. Pretty likely, the programme then is going to crash on de-allocation (when calling `free`, which you actually missed in your example -> memory leak). If you flush stdout before, you might not notice, though... – Aconcagua Sep 09 '19 at 02:32

1 Answers1

2
arr = (float **) malloc(5 * sizeof(float*));
for(int i = 0; i < 5; i++) {
    arr[i] = (float *) malloc(5 * sizeof(float));
}
arr[4][1000] = 6;

"Why does this occur?" - it is undefined behavior. It might work it might not.

Do not attempt to index outside allocation.

Instead:

arr = malloc(sizeof *arr * 5);
assert(arr);
for (int i = 0; i < 5; i++) {
  arr[i] = malloc(sizeof *(arr[i]) * 1001);
  assert(arr[i]);
}
arr[4][1000] = 6;
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256