What happens if I use malloc with the wrong size?

后端 未结 4 1707
[愿得一人]
[愿得一人] 2021-01-15 04:42

I\'m trying to learn more about memory allocation, and so I wrote some test code below to see what would happen if I tried to allocate memory of a less size than what I need

4条回答
  •  隐瞒了意图╮
    2021-01-15 05:33

    It is good that you are doing this kind of exploration. Most standard c libraries include non standard extensions that allow you to check the size of memory after it is allocated. You should call that after returning from malloc and see how much memory the standard library is actually allocating if you want to learn more about how malloc is implemented. You may find that something as simple as malloc(1) can return a sizeable memory chunk.

    As some other readers pointed out, you may be askking malloc to allocate zero bytes in your example code if you were to recompile on a 32 bit system. It will happily comply and return NULL.

提交回复
热议问题