malloc的用法
在堆中申请一块空间,并返回空间的首地址
The malloc() function allocates size bytes and
returns a pointer to the allocated memory.
malloc原型
void *malloc(size_t size);
malloc的实现
使用了一个系统函数sbrk
1
2
3
4
5
6
7
8
9
10
11
12#include <unistd.h>
void *my_malloc(size_t size);
void *my_malloc(size_t size)
{
void *result = NULL;
if((result = sbrk(size)) == (void *)(-1)){
fprintf(stderr, "the memory is full!\n");
return NULL;
}
return result;
}
这种方法只适合申请比较小的内存,而且不能free。。。。
sbrk函数的功能
函数调用成功返回一指针,指向下一个内存空间。函数调用失败则返回(void*)-1,将errno设为ENOMEM。