【问题标题】:Why am I receiving invalid pointer error when running this code为什么我在运行此代码时收到无效指针错误
【发布时间】:2020-05-12 16:34:56
【问题描述】:

我在运行此代码时收到以下错误。

`main' 中的错误:free():无效指针:

我的想法是使用通过 malloc 分配的指针。这是一个示例代码。 请告诉我为什么会收到此错误。

#include <stdio.h>
#include <stdlib.h>
int main()
{
 int c=10;
 int* ptr = NULL;
 ptr = (int*)malloc(sizeof(int));

 if(ptr == NULL)
 {
   printf("Memory not allocated");
   exit(0);
 }

 ptr = &c;
 free(ptr);
 ptr=NULL;
}

【问题讨论】:

  • ptr = &amp;c; 是干什么用的?
  • ptr = malloc(...) 后跟 ptr = &amp;c 类似于例如int a; a = 10; a = 20; 然后想知道为什么a 不再等于10。也许你应该这样做*ptr = c
  • 并注意使用= 的赋值和使用== 进行相等比较之间的区别。您实际上分配给ptr 三次次。
  • 感谢您指出 == 运算符。 *ptr = c 以分段错误结束。我遇到了另一个问题,我将所有不必要的代码都删除到这里。

标签: c pointers free


【解决方案1】:
int c=10;

变量c分配在栈上。

ptr = (int*)malloc(sizeof(int));

将堆上已分配内存的地址分配给ptr

ptr = &c;

c的地址分配给ptr


您的代码中有两个问题。

  1. 内存泄漏。自从您使用重新分配 ptr 后,您丢失了已分配内存的地址。在这种情况下,在程序结束之前,您没有其他方法可以释放在堆上分配的内存。
  2. 您不能使用 free() 函数释放分配在堆栈上的内存。它是自动变量

所以,如果您尝试将 c 的值分配给分配的空间:

*ptr = c;

【讨论】:

    【解决方案2】:

    为什么我会收到 invalid pointer 错误?

    因为你free 的指针不是用malloc(或realloc)分配的。

    你有一个内存泄漏,即你丢失了一个带有ptr = &amp;c的malloced指针,它将c的地址分配给ptr,丢失了malloc返回的值。

    【讨论】:

      【解决方案3】:

      要做到这一点,你需要为这样的指针分配一个指针

      #include <stdio.h>
      #include <stdlib.h>
      
      int main() {
       int c=10;
       int** ptr = NULL;
       ptr = (int**)malloc(sizeof(int*));
      
       if(ptr == NULL)
       {
         printf("Memory not allocated");
         exit(0);
       }
      
       *ptr = &c;
       free(ptr);
       ptr=NULL;
      }
      

      在您的情况下,您正在释放非动态分配的内存并给您带来错误,即使在其他情况下,您也应该始终保留已分配内存的地址以在不再需要时释放它,例如

      #include <stdio.h>
      #include <stdlib.h>
      
      int main() {
       int *ptr1 = (int*)malloc(sizeof(int));
       int *ptr2 = (int*)malloc(sizeof(int));
       *ptr1 = 5;
       *ptr2 = 10;
       // this is wrong because now there is no way to free
       // the address of the allocated memory to ptr1
       ptr1 = ptr2;
       free(ptr1);
       // this gives an error because ptr2 is already free
       free(ptr2);
      }
      

      结论: 如果要分配存储指针,则需要分配指向指针的指针,因此已分配内存的指针会保留,以便在不再需要时释放该内存

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-24
        • 2015-09-06
        • 2010-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多