Segmentation Fault When Accessing Elements in 2D Dynamic Array in C
I'm working with a segmentation fault when trying to access elements in a dynamically allocated 2D array in C. I am using GCC version 10.2.1 on Ubuntu 20.04. My implementation involves allocating memory for a 2D array using pointers, but when I try to set or get values, it crashes. Here's the code I have: ```c #include <stdio.h> #include <stdlib.h> int main() { int rows = 3, cols = 4; int **array = malloc(rows * sizeof(int *)); for (int i = 0; i < rows; i++) { array[i] = malloc(cols * sizeof(int)); } // Trying to set a value array[0][0] = 5; printf("Value at array[0][0]: %d\n", array[0][0]); // Accessing an out-of-bounds index printf("Value at array[3][0]: %d\n", array[3][0]); // This line causes segmentation fault // Free the allocated memory for (int i = 0; i < rows; i++) { free(array[i]); } free(array); return 0; } ``` In this code, the segmentation fault occurs on the line `printf("Value at array[3][0]: %d\n", array[3][0]);`. I realize that I'm trying to access an index that is out of bounds (the valid index range is 0 to 2 for `array`), but I expected to see a different kind of behavior message instead of crashing the program. I've tried adding bounds checking before accessing the array, but this scenario still seems to arise when I attempt to access an invalid index. Is there a specific reason why this is happening, and how can I handle such cases more gracefully? Whatβs the best practice in cases like these to avoid similar crashes? Any insights would be appreciated!