linux内存分配函数

bzero()函数

原型:extern void bzero(void *s, int n)
用法:#include
功能:置字符串s的前n个字节为零且包括’\0’
说明:bzero无返回值,推荐使用memset()代替bzero()函数

1
2
3
4
5
6
7
8
9
10
11
12
#include <syslib.h>
#include <string.h>
int main(){
struct {
int a;
char s[5];
float f;
} tt;
char s[20];
bzero(&tt,sizeof(tt));
...
}

memset()函数

原型:extern void memset(void buffer, int c, int count)
用法:#include
功能:将buffer所指向内存区域的前count个字节置成c
说明:返回指向buffer的指针

1
2
3
4
5
6
7
#include <syslib.h>
#include <string.h>
int main(){
char *s="Golden Global View";
clrscr();
memset(s,'G',6);
}

setmem()函数

原型:extern void setmem(void *buf, unsigned int count, char ch)
功能:把buf所指内存区域前count个字节设置成字符ch
说明:返回指向buf的指针

1
2
3
4
5
6
7
#include <syslib.h>
#include <string.h>
int main(){
char *s="Golden Global View";
clrscr();
setmem(s,6,'G');
}

在LINUX平台上是支持bzero的,但是其并不在ANSI C中定义,也就是不属于C的库函数
在C/C++ code上

1
#define bzero(a, b) memset(a, 0, b)

总结

在初始化内存空间时,尽量使用memset()函数,由于其属于标准C的库函数,而各方面支持的都好。同时,其返回值是指向需分配的buffer的指针,能够进行很好的参数传递。