alloc, malloc, and alloca — What's the difference?

别等时光非礼了梦想. 提交于 2019-12-20 09:35:46

问题


I was under the impression that alloc in Objective-C (when we invoke [anyObject alloc] is actually implementing C function malloc and the memory getting allocated in heap, but could not find anywhere the answer for this.

Also, while searching for alloc, I found alloca which allocates memory in stack. If I am not wrong, alloc allocates memory in heap to create objects.

So, what is the difference between alloc and malloc (and alloca)? Can anyone please summarize?


回答1:


alloc() is not a standard C library function. Some older compilers and libraries contain an <alloc.h> library which provides some memory allocation functions, but this is not standard. The Microsoft Visual C++ runtime includes an Alloc() function which is somewhat similar to malloc(), but this is also not part of the C standard.

malloc() allocates memory on the process heap. Memory allocated using malloc() will remain on the heap until it is freed using free().

alloca() allocates memory within the current function's stack frame. Memory allocated using alloca() will be removed from the stack when the current function returns. alloca() is limited to small allocations.

Situations where alloca() is appropriate are rare. In almost all situations, you should use malloc() to allocate memory.




回答2:


The alloc function is used to allocate a region or block of size bytes in length of the heap.

The malloc function is used to allocate heap storage. Its name stands for memory allocation.




回答3:


I don't remember the verbatim statement from the book C++ Primer, but there is a major difference between the functions. For example new in C++ allocates memory, but it also constructs the data into the memory. The std::allocator allocates memory, but doesn't call any constructor. The same is true for these C functions. One allocates but doesn't construct. One allocates and construct.



来源:https://stackoverflow.com/questions/32685851/alloc-malloc-and-alloca-whats-the-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!