malloc() in C not working as expected

前端 未结 7 791
别那么骄傲
别那么骄傲 2021-01-25 04:52

I\'m new to C. Sorry if this has already been answered, I could\'n find a straight answer, so here we go..

I\'m trying to understand how malloc() works in C. I have this

7条回答
  •  轮回少年
    2021-01-25 05:32

    It works out fine because you're lucky! Usually, a block a little larger than just 2 bytes is given to your program by your operating system.

    If the OS actually gave you 16 bytes when you asked for 2 bytes, you could write 16 bytes without the OS taking notice of it. However if you had another malloc() in your program which used the other 14 bytes, you would write over that variables content.

    The OS doesn't care about you messing about inside your own program. Your program will only crash if you write outside what the OS has given you.

    Try to write 200 bytes and see if it crashes.

    Edit:

    malloc() and free() uses some of the heap space to maintain information about allocated memory. This information is usually stored in between the memory blocks. If you overflow a buffer, this information may get overwritten.

提交回复
热议问题