2
我发布此示例代码以解释我的问题。我试图在函数间传递一个指向整数的指针。如果你编译&运行这个代码,你会看到奇怪的数字出现,我不明白为什么。我认为这是一个坏的使用realloc()
。如果有人可以提供一个提示,或者可能会重定向我一些类似的问题,我会感激。我寻找这个问题,但我找不到任何类似的东西。将指针传递给指针并重新分配空间
#include <stdio.h>
#include <stdlib.h>
void myFunction(int **output);
int main(){
int *indices;
myFunction(&indices);
printf("{");
for(int i=0;i<10;i++){//suppose also for some mysterious reasons that I know min_size in the main
printf("%i,", indices[i]);
}
printf("}\n");
return 0;
}
void myFunction(int **output){
int size = 130;//allocating big amount of space
int* indices = malloc(sizeof(int)*size);
//...start doing mysterious stuffs....
int min_size = 10;
for(int i=0;i<min_size;i++){
indices[i] = i;//just for saving something
}
//...end doing mysterious stuffs...
//now for some reasons I know I need only min_size elements and all other are wasting space so I reallocate
indices = realloc(indices,min_size);//resizing in order to save space
*output = indices;
}
不要重新分配给您传递给'realloc'指针,想一想,如果'realloc'失败并返回'NULL',那么你将失去原始指针并且有内存泄漏。 –
至于你的问题,''realloc'就像'malloc'的大小***以字节为单位***。十个字节与十个'int'元素非常不同。 –
你正在分配'malloc sizeof(int)* size',但是重新分配:'realloc(indices,min_size'。我认为它应该是'realloc(indices,min_size * sizeof(int))' –