Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C语言中的分段错误calloc_C_Linux_Segmentation Fault_Calloc - Fatal编程技术网

C语言中的分段错误calloc

C语言中的分段错误calloc,c,linux,segmentation-fault,calloc,C,Linux,Segmentation Fault,Calloc,我正在编写一个C程序,它占用了calloc、malloc和alloca进程的平均时间。我得到了所有要编译的东西,但是当我运行它时,我得到了一个分段错误。它运行的第一件事是calloc,所以我假设问题从这里开始 这是我的calloc函数,malloc和alloca基本上是相同的,所以我想现在还没有理由发布它们 double calloctest(int objectsize, int numberobjects, int numberoftests) { double average =

我正在编写一个C程序,它占用了calloc、malloc和alloca进程的平均时间。我得到了所有要编译的东西,但是当我运行它时,我得到了一个分段错误。它运行的第一件事是calloc,所以我假设问题从这里开始

这是我的calloc函数,malloc和alloca基本上是相同的,所以我想现在还没有理由发布它们

double calloctest(int objectsize, int numberobjects, int numberoftests)
{
    double average = 0;
    for (int i = 0; i < numberoftests; i++)
    {
            clock_t begin = clock();
            int *objectsize = calloc(numberobjects, sizeof(char) * *objectsize);
            clock_t end = clock();
            double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
            average = average + time_spent;
            printf("%f", time_spent);
            free(objectsize);
    }
    double totalAverage;
    totalAverage = average / numberoftests;
    return totalAverage;
}
double calloctest(int objectsize、int numberobjects、int numberoftests)
{
双平均=0;
for(int i=0;i
您有一个局部变量
objectsize
,该变量对同名函数参数进行阴影处理,在存储
calloc()
的返回值之前取消对该变量的引用:

你可能想写:

int *object = calloc(numberobjects, objectsize);
...
free(object);

因为您有
sizeof(char)**objectsize
A)
objectsize
不是指针。B)
sizeof(char)
1
。您可以使用
calloc(numberobjects,objectsize)
非常感谢,malloc和alloca是否以相同的速度做事?我还打印了我的速度,malloc和alloca都得到了相同的速度。
int *object = calloc(numberobjects, objectsize);
...
free(object);