Malloc () and heap memory

I get a weird result in the following C code.

int main()
{
    int *p = (int *) malloc(100);
    p[120] = 5;
    printf("\n %d", p[120]);
}

Since I allocated only 100 bytes, this code should cause a segmentation error. However, it prints "5" and does not give any runtime error. Can someone explain the reason?

+5
source share
6 answers

No, the code should not (necessarily) give segfault. Segfault occurs when you try to access a virtual memory page that is not allocated to your process.

A “heap” or “free store” is an area of ​​virtual memory pages belonging to your process. The API malloc()subdivides this area into blocks and returns a pointer to a block.

, , , , . , , malloc() .

:

: Microsoft Bug-Free C Steve Maguire alt text http://ecx.images-amazon.com/images/I/5148TK6JCVL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35, -76_AA240_SH20_OU01_.jpg

: , , , . , . , . . , 99% , , . , , 99%.

+20

, . , , - .

+6

, segfault, . . C - , , . "" C, . .

C ( ++) , , Ada.

+3

, . - , .

0

; C, . .

0

:

  • .

    int * x = 0;

    x = 200;/ */

Segfaults are thrown by MMU exceptions based on what is defined as illegal memory access. Depending on how the OS structures its memory, one memory access on the OS may be legal (albeit incorrect), and on another OS it may be illegal.

0
source

All Articles