【发布时间】:2017-01-31 15:54:19
【问题描述】:
我试图写一个函数来找到两个数组的交集
我只是不明白为什么它不能很好地工作。这是我的功能:
int* IntersectionOfArrays(int* arr1, int size1, int* arr2, int size2, int* sizeRes)
{
int* res=(int*)malloc(1*sizeof(int)); //res is the array of the resolution of intersection//
int i = 0, j = 0;
*sizeRes = 0;
merge_sort(arr1,0, size1-1); //sorting the arrays//
merge_sort(arr2,0, size2-1);
while (i < size1 && j < size2)
{
if (arr1[i] < arr2[j])
i++;
else if (arr1[i] > arr2[j])
j++;
else
{
res[*sizeRes] = arr1[i]; //getting the same elements of the two arrays - the intersection values//
i++;
j++;
(*sizeRes)++;
res = (int*)realloc(res, 1*sizeof(int)); //allocating more memory as required - according to the size of res(intersection)//
}
}
if (*sizeRes==0) //if the intersection is empty
return NULL;
return res;
}
此函数可以编译,但由于我收到垃圾项目,因此无法按预期工作。 我想知道这个功能应该如何修复。
【问题讨论】:
-
res = (int*)realloc(res, 1*sizeof(int));-->res = realloc(res, (*sizeRes + 1) * sizeof(int)); -
建议最初分配
size1 * sizeof int和size2 * sizeof int的最小值。这是您可能需要的最大值。如果您愿意,在您知道所需大小时,在循环之后缩小该分配。作为奖励,如果交集为空,则realloc()ing 将大小设为零会释放整个分配,从而修复当前代码遭受的内存泄漏。 -
还有
return NULL;:你有内存泄漏。 -
在调用
realloc()时,始终将返回值保存到临时指针中,然后检查 (!=NULL) 该指针以确保操作成功。否则当realloc()失败时,原始指针丢失,导致不可恢复的内存泄漏
标签: c arrays dynamic-memory-allocation