#include <stdlib.h> int main() { int i = 0; unsigned char (*b)[5]; b = malloc( 5 ); for ( ; i < 100 ; i++ ) { *(b+i)[0] = 192; *(b+i)[1] = 168; *(b+i)[2] = 0; *(b+i)[3] = 1+i; printf( "%d.%d.%d.%d\n", *(b+i)[0], *(b+i)[1], *(b+i)[2], *(b+i)[3] ); } return 0; } 

In my understanding, the malloc () function allocates only 5 bytes, and at least at the 6th step of the cycle (i == 5) the pointer should go beyond the memory allocated to the process, why does this not happen?

I collect using gcc version 4.9.2 (Debian 4.9.2-10)

  • four
    Do you know what is undefined behavior? He did undefined. - Harry
  • 2
    Because the memory page size is 4096 bytes (by default, so to say, a “quantum” of memory), and fail can occur only if the next page is not made allocate, so even going beyond 4096 there may or may not be a fail. While the program is small, such tricks can end in nothing, and with a large program you can get glitches that are very difficult to catch. - nick_n_a
  • If you have a task to get seg-fail, you can try to read / write in 4096 byte increments. - nick_n_a
  • The task is just the same - it will not stumble when using large structures =) Thank you for your clarification, indeed - as the size of the array increases to [4096], the fall occurs at the 30th step - Andrew Day
  • one
    You are very mistaken in the conclusions. It is impossible to go beyond the allocated memory array uniquely. if sfail did not happen - you can write to the memory of a neighboring object - and for a long time you won’t understand why the program gives a strange bug (the objects will suddenly be equal to strange values). Even worse, if you damage the memory structure during malloc, then your memory functions "suddenly" will stop working for an "incomprehensible" reason, which you may not find soon. - nick_n_a

2 answers 2

From the comment by @nick_n_a :

Because the memory page size is 4096 bytes (by default, so-called “quantum” of memory), and fail can occur only if no allocate is made for the next page. Therefore, even going over the edge of 4096 fail and may or may not be. While the program is small, such tricks can end in nothing, and with a large program you can get glitches that are very difficult to catch.

If you have a task to get seg-fail, then you can try to read / write in 4096 byte increments.

    The fact is that malloc allocates memory from a heap - a pre-allocated range of pages of memory. In the heap lie all the fragments allocated by malloc , plus the service data of the heap itself.

    Accordingly, when you try to access (read or write) outside of the range of memory allocated to you, you are still in the range of memory for the heap (therefore, there is no drop). However, you climb:

    • or to the area requested by another part of your program (then the fall will occur if the data is not correctly interpreted),
    • or to the service structures (then the crash will occur at the next request / release of the heap block).