0

The following code snippet prints beyond the allocated the range.It is printing <127, beyond that segmentation fault occurs. But my intention is beyond allocated range it should get segmentation fault,it is not happening why?. Please suggest.

int main ()
{
  char *ptr;
  char i = 0;
  ptr = malloc (5);

  for (i = 0; i < 127; i++)
      *(ptr + i) = i;
  for (i = 0; i < 127; i++)
      printf ("value %d\n", *(ptr + i)); 

  return 0;
}
umesh
  • 1
  • 1
  • 1
    "segmentation fault" is not a guaranteed outcome of *undefined behaviour* – pmg Apr 23 '20 at 14:48
  • `for (i = 0; i < 127; i++) { if (i >= 5) { fprintf(stderr, "buffer overflow\n"); exit(EXIT_FAILURE); } *(ptr + i) = i; }` – pmg Apr 23 '20 at 15:01
  • Maybe the part of the memory just behind allocated ptr is not "protected". Your program must reach a protected part of the memory to throw segmentation fault. – vivi17 Apr 23 '20 at 15:05
  • The earlier comment about seg fault not guaranteed is correct. C does not carefully check that you don't write out of bounds, and immediately throw like many languages. It just lets you scribble on the wall. A segfault only results when your scribbling happens to break something else. It's not simple to predict. In any case, the segfault is not really a response to your out-of-bounds at all. It's an indirect result which happens when it happens. – T W Bennet Apr 23 '20 at 16:44

0 Answers0