C++ dynamically allocated memory

前端 未结 8 1850
难免孤独
难免孤独 2020-12-10 16:16

I don\'t quite get the point of dynamically allocated memory and I am hoping you guys can make things clearer for me.

First of all, every time we allocate memory we

8条回答
  •  醉梦人生
    2020-12-10 16:54

    Whenever you are using new in C++ memory is allocated through malloc which calls the sbrk system call (or similar) itself. Therefore no one, except the OS, has knowledge about the requested size. So you'll have to use delete (which calls free which goes to sbrk again) for giving memory back to the system. Otherwise you'll get a memory leak.

    Now, when it comes to your second case, the compiler has knowledge about the size of the allocated memory. That is, in your case, the size of one int. Setting a pointer to the address of this int does not change anything in the knowledge of the needed memory. Or with other words: The compiler is able to take care about freeing of the memory. In the first case with new this is not possible.

    In addition to that: new respectively malloc do not need to allocate exactly the requsted size, which makes things a bit more complicated.

    Edit

    Two more common phrases: The first case is also known as static memory allocation (done by the compiler), the second case refers to dynamic memory allocation (done by the runtime system).

提交回复
热议问题