malloc() in C not working as expected

前端 未结 7 718
别那么骄傲
别那么骄傲 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条回答
  •  旧时难觅i
    2021-01-25 05:35

    Won't this cause a buffer overflow if I enter a string with more than two characters?

    Absolutely. However, C does no bounds checking at runtime; it assumes you knew what you were doing when you allocated the memory, and that you know how much is available. If you go over the end of the buffer, you will clobber whatever was there before.

    Whether that causes your code to crash or not depends on what was there before and what you clobbered it with. Not all overflows will kill your program, and overflow in the heap may not cause any (obvious) problems at all.

提交回复
热议问题