所需头文件
#include <alloca.h>
alloca:allocate memory that is automatically freed
申请能够自动释放的内存(实际上是栈区的内存)
void *alloca(size_t size);
The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.
alloca函数从调用者的栈帧上申请size byte大小的空间,当调用alloca的函数返回的时候这个临时的空间会被自动释放。
返回值
The alloca() function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behavior is undefined.
#include <alloca.h>
alloca:allocate memory that is automatically freed
申请能够自动释放的内存(实际上是栈区的内存)
void *alloca(size_t size);
The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.
alloca函数从调用者的栈帧上申请size byte大小的空间,当调用alloca的函数返回的时候这个临时的空间会被自动释放。
返回值
The alloca() function returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behavior is undefined.
alloca函数返回一个指向已申请到的内存的头部的指针,如果alloca分配内存导致栈溢出,程序的行为是未定义的
alloca跟malloc的区别是alloca申请的内存是在栈上,能够自动释放(禁止用free去释放alloca所分配的内存!),而malloc分配的内存是在堆上,需要使用free释放所分配的内存,具体举个例子来说明区别:
#include <alloca.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
const char *src = "hello";
printf("before alloc\n");
sleep(30);
for (char *des1; strcmp(des1, src) != 0; ) {
des1 = (char *)alloca(sizeof(char) * 100000);
strcpy(des1, src);
printf("alloc now\n");
sleep(10);
printf("alloc end\n");
}
sleep(20);
for (char *des2; strcmp(des2, src) != 0; ) {
des2 = (char *)malloc(sizeof(char) * 100000);
strcpy(des2, src);
printf("malloc now\n");
sleep(10);
printf("malloc end\n");
}
sleep(20);
return 0;
}
运行该程序,找到对应的pid,用pmap $pid(对应pid)可以看到该程序所消耗的memory(或者用top -d 1 -p $pid)就可以每秒打印一次该进程所消耗的内存,结果发现alloca所分配的内存不会导致进程占用内存增大,但是malloc分配的内存会导致进程占用的内存增大,这个就说明了alloca分配的是栈内存(预先分配好),malloc分配的是堆内存(随用随分配)