Search code examples
cdynamic-memory-allocation

Why can I assign a value to unallocated memory in my float 2d array in c?


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?


Solution

  • 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;