C-realloc() : invalid pointer error encoutered

标签 c

我一直在尝试 O(n ^2) 排序算法只是为了练习 C,但遇到了这个恼人的“realloc():无效指针”错误,并且无法找出原因。我看过其他解释,但它们没有太大帮助。

    #include <stdio.h>
    #include <stdlib.h>

    int* removeIndex(int* list, int index, int len){
        for(int i = index; i < len - 1; i++){
            list[i] = list[i+1];
        }
        return realloc(list, len - 1);
    }

    int* sort(int* unsorted, int len){
         int* sorted = malloc(len * sizeof(int));

         for(int placement = 0; placement < len; placement++){
             int smallest_index = 0;
             int smallest = unsorted[smallest_index];
             int len_unsorted = len - placement;

             for(int i = 0; i < len_unsorted; i++){
                if (unsorted[i] < smallest){
                    smallest = unsorted[i];
                    smallest_index = i;
                }    
             }

             unsorted = removeIndex(unsorted, smallest_index, len_unsorted);
             sorted[placement] = smallest;
         }

        return sorted;
    }

    int main()
    {
        int len = 5;
        int unsorted[5] = {5,4,3,2,1};

        int* sorted = sort(unsorted, len);

        for(int i = 0; i < len; i++){
            printf("%d\n", sorted[i]);
        }
        return 0;
    }

顺便说一句,为什么我写的时候会出现错误

int len = 5;
int unsorted[len] = {5,4,3,2,1};

所以我必须强制将其写为 int unsorted[5] = {5,4,3,2,1};

干杯

最佳答案

传递给realloc的指针指向一个具有自动存储持续时间的数组,该数组在main()中声明和初始化,而不是指向先前分配的内存块使用 malloccallocrealloc

来自realloc [强调]

Reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed with a call to free or realloc. Otherwise, the results are undefined.

关于C-realloc() : invalid pointer error encoutered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51456093/

相关文章:

c - 为什么在更改源文件时 make 不重建?

c - 泛型链表中的自由类型转换

c - 如何使用 c 中的套接字 api 一次性发送 .bmp 文件?

c - 从结构中删除元素

c sizeof() 导致溢出?

转换两个指针(float* 到 int*)

比较 char 数组与 uint8_t 数组与 int8_t 数组的访问时间

c - 带有 mmap 的 shm_open 仅在一台特定机器上给出总线错误

c - 通过信号量访问共享内存

c - 如何在 GtkEventBox 中设置 GtkWindow 的不透明度