相关疑难解决方法(0)

为什么malloc + memset比calloc慢?

众所周知,它与初始化分配的内存calloc不同malloc.使用时calloc,内存设置为零.使用时malloc,内存不会被清除.

所以在日常工作中,我认为callocmalloc+ 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)

更换 …

c malloc

249
推荐指数
2
解决办法
5万
查看次数

为什么malloc在gcc中将值初始化为0?

也许从平台到平台不同,但是

当我使用gcc编译并运行下面的代码时,我每次都在ubuntu 11.10中得到0.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    double *a = (double*) malloc(sizeof(double)*100)
    printf("%f", *a);
}
Run Code Online (Sandbox Code Playgroud)

为什么malloc表现得像这样,即使有calloc?

是不是意味着只是将值初始化为0会产生不必要的性能开销,即使您有时不想要它也是如此?


编辑:哦,我之前的例子不是initiazling,但碰巧使用"新鲜"块.

我正在寻找的是为什么它在分配一个大块时初始化它:

int main()
{
    int *a = (int*) malloc(sizeof(int)*200000);
    a[10] = 3;
    printf("%d", *(a+10));

    free(a);

    a = (double*) malloc(sizeof(double)*200000);
    printf("%d", *(a+10));
}

OUTPUT: 3
        0 (initialized)
Run Code Online (Sandbox Code Playgroud)

但感谢您指出在进行mallocing时存在安全原因!(没想过).当分配新块或大块时,它必须初始化为零.

c linux malloc gcc

76
推荐指数
4
解决办法
4万
查看次数

标签 统计

c ×2

malloc ×2

gcc ×1

linux ×1