Understanding malloc and pointer incrementation with free

This question already has an answer here:

  • What happens if I try to access memory beyond a malloc()'d region? 5 answers

  • What you are doing is undefined behavior.

    int *p = (int *) malloc(sizeof(int));
    

    This allocates sizeof(int) bytes starting from the address returned by malloc .

    When you do

    *(p+1) = 41;
    

    you are dereferencing to a memory location which has not been allocated on the heap. Its address is p + sizeof(int) which is an not managed address.

    This yields undefined behavior and every conclusion you can draw by observing the results is irrelevant .

    链接地址: http://www.djcxy.com/p/80404.html

    上一篇: C malloc和免费

    下一篇: 了解malloc和指针增量与免费