Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.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和valgrind-为什么在没有空闲时间的情况下使用malloc时没有内存泄漏_C_Valgrind - Fatal编程技术网

c和valgrind-为什么在没有空闲时间的情况下使用malloc时没有内存泄漏

c和valgrind-为什么在没有空闲时间的情况下使用malloc时没有内存泄漏,c,valgrind,C,Valgrind,运行valgrind我发现一切正常-总堆使用率:2个allocs,2个free,分配了1028字节。为什么我不需要在函数bubbleSort上释放temp #include <stdio.h> #include <stdlib.h> void bubbleSort(int numbers[], int array_size) { int i, j; int *temp; for (i = (array_size - 1); i > 0; i

运行
valgrind
我发现一切正常-
总堆使用率:2个allocs,2个free,分配了1028字节
。为什么我不需要在函数
bubbleSort
上释放
temp

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

void bubbleSort(int numbers[], int array_size) {
    int i, j;
    int *temp;
    for (i = (array_size - 1); i > 0; i--) {
        for (j = 1; j <= i; j++) {
            if (numbers[j - 1] > numbers[j]) {
                temp = (int *) malloc(sizeof(int *));
                *temp = numbers[j - 1];
                numbers[j - 1] = numbers[j];
                numbers[j] = *temp;
            }
        }
    }
}

int main(int argc, char **argv) {
    char **arr = argv + 1;
    int i, n = argc - 1;

    int *numbers = (int *) calloc(n, sizeof(int));

    printf("Original array:");
    for (i = 0; i < n; ++i) {
        printf(" %s", arr[i]);
        numbers[i] = atoi(arr[i]);
    }
    printf("\n");

    bubbleSort(numbers, n);

    printf("Sorted array:");
    for (i = 0; i < n; ++i)
        printf(" %d", numbers[i]);
    printf("\n");

    free(numbers);
    return 0;

}
#包括
#包括
void bubbleSort(整数[],整数数组大小){
int i,j;
内部*温度;
对于(i=(数组大小-1);i>0;i--){
对于(j=1;j个数[j]){
temp=(int*)malloc(sizeof(int*));
*温度=数字[j-1];
数字[j-1]=数字[j];
数字[j]=*温度;
}
}
}
}
int main(int argc,字符**argv){
字符**arr=argv+1;
int i,n=argc-1;
int*numbers=(int*)calloc(n,sizeof(int));
printf(“原始数组:”);
对于(i=0;i
您将哪些参数传递给您的程序?特别是,如果数组已经排序,则不会执行malloc。顺便说一下,您在
temp=(int*)malloc(sizeof(int*))处有一个bug:应为
sizeof(int)
。当然,无论如何,使用
malloc
进行此操作都有点愚蠢。不过,您肯定存在漏洞,而且无论如何都应该释放
temp
。当我使用参数
5 4 3 2 1
运行此程序时,valgrind报告
12 allocs,2释放
,如预期的那样。明白了。只输入1个数字,因此不需要排序。谢谢你把什么参数传递给你的程序?特别是,如果数组已经排序,就不会执行malloc:应为
sizeof(int)
。当然,无论如何,使用
malloc
进行此操作都有点愚蠢。不过,您肯定存在漏洞,而且无论如何都应该释放
temp
。当我使用参数
5 4 3 2 1
运行此程序时,valgrind报告
12 allocs,2释放
,如预期的那样。明白了。只输入1个数字,因此不需要排序。谢谢