众所周知,它与初始化分配的内存calloc不同malloc.使用时calloc,内存设置为零.使用时malloc,内存不会被清除.
所以在日常工作中,我认为calloc是malloc+ memset.顺便说一下,为了好玩,我为基准编写了以下代码.
结果令人困惑.
代码1:
#include<stdio.h>
#include<stdlib.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)calloc(1,BLOCK_SIZE);
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
代码1的输出:
time ./a.out
**real 0m0.287s**
user 0m0.095s
sys 0m0.192s
Run Code Online (Sandbox Code Playgroud)
代码2:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)malloc(BLOCK_SIZE);
memset(buf[i],'\0',BLOCK_SIZE);
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
代码2的输出:
time ./a.out
**real 0m2.693s**
user 0m0.973s
sys 0m1.721s
Run Code Online (Sandbox Code Playgroud)
更换 …
gcc 4.5.1 c89
Run Code Online (Sandbox Code Playgroud)
我已经编写了这个源代码,以便我更好地理解malloc和calloc.
我理解,但只是有几个问题.
dev = malloc(number * sizeof *devices);
Run Code Online (Sandbox Code Playgroud)
等于这个calloc.我并不担心清理内存.
dev = calloc(number, sizeof *devices);
Run Code Online (Sandbox Code Playgroud)
与在while循环中执行5次相比,这究竟是什么呢?
dev = malloc(sizeof *devices);
Run Code Online (Sandbox Code Playgroud)
我想第一个和第二个是创建一个指向5结构设备的指针.第三个是创建一个指向结构设备的指针?
我的程序说明了使用valgrind编译和运行的3种不同方法--leak-check = full.
非常感谢任何建议.
#include <stdio.h>
#include <stdlib.h>
struct Devices {
#define MAX_NAME_SIZE 80
size_t id;
char name[MAX_NAME_SIZE];
};
struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);
int main(void)
{
size_t num_devices = 5;
size_t i = 0;
struct Devices *device = NULL;
struct Devices *dev_malloc = NULL;
struct Devices *dev_calloc = NULL;
for(i = 0; …Run Code Online (Sandbox Code Playgroud)