有一段时间我一直在努力研究 C 中的指针,但我似乎陷入了一个与内存有关的问题。我正在开发一个函数,它多次从另一个函数返回一个数组,然后最后应该释放该数组。返回数组一次就可以了,但是如果我尝试多次返回数组,那么一旦程序中止,我就会收到段错误。该函数的代码为
double func(int n, int max, int s){
int i;
int *p;
int *q;
double diff_t;
//start timer
time_t start_t, end_t;
time(&start_t);
//generate the arrays and search for s
for(i=0;i<100;++i){
p=initarray(n,max);
q=sort(n,p);
search(s,n,q);
}
//calculate elapsed time
time(&end_t);
diff_t=difftime(end_t,start_t);
//deallocate array
free(p);
return(diff_t);
}
该函数中使用的其他函数是
int *initarray(int n, int max){
//allocate memory for the array
int *arr=malloc(n);
//initialize an array
....
//return the array
return(arr);
}
int *sort(int n, int *arr){
//sort the array
...
//return the array
return(arr);
}
int search(int i, int n, int *arr){
int j;
int index;
//search the array for i
...
//return the index of i in the array
return(index);
}
然后我在主函数中调用 func
func(2000,10000,10)
此外,例如,每当我尝试使用 free(p) 取消分配数组时,程序都会中止并返回双重释放或损坏错误。所以我基本上有两个问题:我无法让我的函数多次返回数组,并且最终无法释放数组。我在互联网上到处搜索,但没有任何效果,所以任何帮助将不胜感激!
最佳答案
我觉得问题很简单。您正在多次分配内存。但你只释放内存一次。即:最后分配的内存块。只需将 free(p) 语句移至 for 循环内即可。
for(i=0;i<100;++i)
{
p=initarray(n,max);
q=sort(n,p);
search(s,n,q);
//deallocate array
free(p);
}
关于c - 多次从函数返回数组并释放 C 中的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43293570/