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个数字,因此不需要排序。谢谢