Segmentation Fault When Accessing Members of Struct with Dynamically Allocated Memory in C
I'm working with a segmentation fault when trying to access the members of a struct that I've dynamically allocated memory for. My struct is defined as follows: ```c typedef struct { int id; char name[50]; } Student; ``` I am attempting to create an array of `Student` structs dynamically and access its members like this: ```c #include <stdio.h> #include <stdlib.h> int main() { int n = 5; Student *students = malloc(n * sizeof(Student)); if (students == NULL) { perror("Failed to allocate memory"); return EXIT_FAILURE; } for (int i = 0; i < n; i++) { students[i].id = i + 1; snprintf(students[i].name, sizeof(students[i].name), "Student %d", students[i].id); } // Accessing members incorrectly for (int i = 0; i <= n; i++) { // <- Off by one behavior printf("ID: %d, Name: %s\n", students[i].id, students[i].name); } free(students); return 0; } ``` I've noticed that the loop that accesses the `students` array goes one index beyond what I've allocated (i.e., `i <= n` instead of `i < n`). This leads to a segmentation fault when trying to access `students[n]`, which is outside of the allocated memory. However, I expected that accessing this out-of-bounds memory would not crash the program but rather print garbage values or cause undefined behavior without crashing. Is there any way to handle this more gracefully, or is it typical to run into segmentation faults when accessing out-of-bounds memory in C? I also tried using tools like `valgrind`, which confirmed that the scenario is indeed due to accessing invalid memory. How can I prevent this type of behavior in the future?