"没有分配被释放的指针." malloc之后的错误,realloc

OJF*_*ord 5 c pointers dynamic-arrays

我有以下代码的错误:

int main(){
    point   *points = malloc(sizeof(point));
    if (points == NULL){
        printf("Memory allocation failed.\n");
        return 1;
    }
    other_stuff(points);
    free(points);
    return 0;
}
void other_stuff(point points[]){
    //stuff
    realloc(points, number*sizeof(point))
}
Run Code Online (Sandbox Code Playgroud)

我搜索过,但只找到了很明显没有分配的例子.

在这里,我曾经malloc初始化points,后来改变了它的大小realloc; 那么当我来到free它时,指针"未分配"怎么样?

Flo*_*ris 8

realloc可能会将内存移动到新位置(如果没有足够的空间来扩展旧指针).如果发生这种情况,您需要释放新指针.

试试这个调整:

int main(){
    point   *points = malloc(sizeof(point));
    if (points == NULL){
        printf("Memory allocation failed.\n");
        return 1;
    }
    other_stuff(&points);
    free(points);
    return 0;
}
void other_stuff(point **points){
    //stuff
    point *temp = realloc(*points, number*sizeof(point));
    if(temp != NULL) {
      *points = temp;
      // and do your stuff
    }
    else {
      // panic? memory reallocation failed. Deal with it gracefully.
    }
}
Run Code Online (Sandbox Code Playgroud)

通过传递一个句柄other_stuff,我们给它不仅控制了当指针指向的地方,但指针本身的地址.这允许它移动内存.句柄是动态管理内存的好方法; 但从概念上讲,指针指针需要一些习惯......