Unexpected 'Segmentation Fault' When Running a C Program on Ubuntu 22.04 with Custom Libraries
I'm reviewing some code and I'm following best practices but I've been struggling with this for a few days now and could really use some help. I'm working with a frustrating scenario while trying to run my C program on Ubuntu 22.04. The program compiles without any errors, but when I execute it, I get a 'Segmentation fault' behavior. Hereβs a snippet of the code that I'm trying to run: ```c #include <stdio.h> #include <stdlib.h> int main() { int *arr = malloc(10 * sizeof(int)); if (!arr) { perror("Failed to allocate memory"); return EXIT_FAILURE; } for (int i = 0; i <= 10; i++) { // <-- Notice the out-of-bounds access here arr[i] = i; } free(arr); return 0; } ``` The question arises from the loop where I mistakenly try to access `arr[10]`, which is out of bounds since the valid indices are from 0 to 9. I thought running this in gdb might help, so I used the following commands: ```bash gdb ./my_program run ``` Upon running, gdb outputs: ``` Program received signal SIGSEGV, Segmentation fault. 0x0000000000401138 in main () ``` After realizing the out-of-bounds scenario, I've changed the loop condition to `i < 10`, but I'm still experiencing a segmentation fault before reaching this point. I have also tried checking for memory leaks using Valgrind: ```bash valgrind ./my_program ``` Valgrind does not report any memory leaks, but I still get a segmentation fault when running it normally. Is there some hidden memory corruption or another scenario that could cause this behavior? How can I debug this to find the exact reason for the segmentation fault? This is part of a larger CLI tool I'm building. I'm using C latest in this project. Thanks in advance! The project is a REST API built with C.