Issues with pointer arithmetic leading to unexpected behavior in C
I'm trying to implement I've been banging my head against this for hours... I'm encountering unexpected behavior when performing pointer arithmetic with a dynamically allocated array in C. I'm using GCC version 11.2.0 and trying to create a simple program that manipulates integer arrays. The following code snippet demonstrates my approach: ```c #include <stdio.h> #include <stdlib.h> int main() { int *arr = malloc(5 * sizeof(int)); if (arr == NULL) { perror("Failed to allocate memory"); return 1; } for (int i = 0; i < 5; i++) { arr[i] = i + 1; } // Incorrect pointer arithmetic int *ptr = arr + 3; printf("Value at ptr: %d\n", *ptr); // Trying to access out of bounds ptr += 3; printf("Value at ptr after increment: %d\n", *ptr); free(arr); return 0; } ``` When I run the program, I notice that after incrementing `ptr`, I sometimes get a segmentation fault. I expected that accessing `ptr` after incrementing it by 3 would give me an out-of-bounds access warning rather than crashing the program. I've tried using `valgrind` to check for memory issues, and I'm not seeing memory leaks, but I suspect that my pointer arithmetic may be flawed. Shouldn't accessing beyond the allocated bounds result in a defined behavior instead of a crash? What am I doing wrong here? Any insights on how to handle pointer arithmetic safely would be greatly appreciated! Am I missing something obvious? What am I doing wrong? I'm coming from a different tech stack and learning C. I'm working with C in a Docker container on Debian. Is this even possible? This is my first time working with C 3.11. I appreciate any insights!