Why, or when, do you need to dynamically allocate memory in C?

前端 未结 3 541
日久生厌
日久生厌 2020-11-29 02:04

Dynamic memory allocation is a very important topic in C programming. However, I\'ve been unable to find a good explanation of what this enables us to do, or why it is requi

3条回答
  •  长情又很酷
    2020-11-29 02:23

    Dynamic allocation is required when you don't know the worst case requirements for memory. Then, it is impossible to statically allocate the necessary memory, because you don't know how much you will need.

    Even if you know the worst case requirements, it may still be desirable to use dynamic memory allocation. It allows for the system memory to be used more efficiently by multiple processes. All processes could statically commit their worst case memory requirements, but that puts a cap on how many running processes can exist on the system. If it is never the case that all processes use the worst case at the same time, then the system memory constantly runs underutilized, which is a waste of resources.

    As to your side question, you should not cast the result of a call to malloc() in C. It can hide the bug of a missing declaration (implicit declarations were permitted prior to C.99), and results in undefined behavior. Always prefer taking the result of malloc() without a cast. malloc() is declared to return void *, and in C, a conversion between void * and another pointer type is always permitted (modulo type qualifiers like const).

提交回复
热议问题