-2

I wrote the following after noticing something weird happening in another project. This code does not produce a segfault even though arrays are being called out of bounds multiple times. Can someone explain to me why there is no segfault from running the code below?

#include <stdlib.h>
#include <stdio.h>
int main()
{
    int *a = (int *)malloc(4 * sizeof(int));
    int *b = (int *)malloc(3 * sizeof(int));
    int i = 0;
    for(i =0; i <3 ; i++)
    {   
     b[i] =  3+i;
    }   
    for(i = 0; i < 4; i++)
    {   
     a[i] = i;
    }   
    for(i = 0; i < 100 ; i++){
     a[i] = -1; 
    }   
    for(i = 0 ; i < 100 ; i++){
    printf("%d \n", b[i]);
    }   
}
MYV
  • 4,294
  • 6
  • 28
  • 24

4 Answers4

2

Undefined behaviour is undefined. Anything can happen, including the appearance of "correct" behaviour.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
2

A segfault only happens if you try to access memory locations that are not mapped into your process.

The mallocs are taken from bigger chunks of preallocated memory that makes the heap. E.g. the system may make (or increase) the heap in 4K blocks, so reaching beyond the the bounds of your arrays will still be inside that block of heap-memory that is already allocated to your process (and from which it would assign memory for subsequent mallocs).

In a different situation (where more memory was allocated previously, so your mallocs are near the end of a heap block), this may segfault, but it is basically impossible to predict this (especially taking into account different platforms or compilers).

QSQ
  • 446
  • 2
  • 5
1

A segmentation fault occurs when a process tries to access memory which OS accounts as not belonging to the process. As memory accounting inside an OS is done by pages (usually 1 page = 4 KB), a process can access any memory within the allocated page without OS noticing it.

nullptr
  • 11,008
  • 1
  • 23
  • 18
1
  1. Should be using new and not malloc
  2. What is the platform?
  3. When you try undefined behaviour - gues what it is undefined.
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • isn't new just syntactic sugar for malloc? – MYV Jun 11 '13 at 20:34
  • 1
    @Maksim - No - For a start it calls a contructor if necessary and perhaps the underlying mechanism uses a different method to allocate the memory. – Ed Heal Jun 11 '13 at 20:52