alloc,malloc和alloca —有什么区别? [英] alloc, malloc, and alloca — What's the difference?

查看:217
本文介绍了alloc,malloc和alloca —有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给我的印象是,Objective-C中的alloc(当我们调用[anyObject alloc]时实际上正在实现C函数malloc,并且在堆中分配了内存,但是找不到任何答案). /p>

此外,在搜索alloc时,我发现alloca可以在堆栈中分配内存.如果我没看错,alloc在堆中分配内存以创建对象.

那么,allocmalloc(以及alloca)之间有什么区别?有人可以总结一下吗?

解决方案

alloc()不是标准的C库函数.一些较旧的编译器和库包含<alloc.h>库,该库提供了一些内存分配功能,但这不是标准的. Microsoft Visual C ++运行时包含一个Alloc()函数,该函数与malloc()有点相似,但这也不是C标准的一部分.

malloc()在进程堆上分配内存.使用malloc()分配的内存将保留在堆上,直到使用free()释放它为止.

alloca()在当前函数的堆栈帧内分配内存.当当前函数返回时,使用alloca()分配的内存将从堆栈中删除. alloca()仅限于小额分配.

alloca()合适的情况很少见.在几乎所有情况下,都应使用malloc()分配内存.

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?

解决方案

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.

这篇关于alloc,malloc和alloca —有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆