【问题标题】:What is causing this "store to address with insufficient space" error?是什么导致此“存储空间不足的存储地址”错误?
【发布时间】:2020-06-18 16:44:11
【问题描述】:
    struct ListNode {
        int val;
        struct ListNode *next;
    };


   struct ListNode* test = malloc(sizeof(struct ListNode*));

   test->val = 6;

   struct ListNode* lex = malloc(sizeof(struct ListNode*));

   test->next = lex;

   return test;

此时我应该收到一个填充的结构。相反,我得到了这个:

   Line 14: Char 18: runtime                                                    
   error: store to address   
   0x602000000118 with      
   insufficient space for an 
   object of type 'struct ListNode 
   *' (solution.c)


   0x602000000118: note: pointer   
   points here

   be be be be  00 00 00 00 00 00 
   00 00  02 00 00 00 ff ff ff 02  
   08 00 00 20 01 00 80 70  be be 
   be be

这是怎么回事?

【问题讨论】:

    标签: c pointers malloc sizeof


    【解决方案1】:

    您只是为 ListNode 指针分配空间,而不是实际的 ListNode。

    试试:struct ListNode* test = malloc(sizeof(struct ListNode));

    【讨论】:

      【解决方案2】:

      我们来看看这行代码:

      struct ListNode* test = malloc(sizeof(struct ListNode*));
      

      指针test 想要指向一个足够大的内存块来容纳一个实际的、诚实的struct ListNode 对象。该对象中有一个整数和一个指针。

      但是,您对malloc 的调用说“请给我足够的空间来存储指向struct ListNode 对象的指针。”这没有足够的内存来保存struct ListNode,因此出现了错误。

      解决此问题的一种方法是在您的sizeof 调用中从struct ListNode 中删除星号:

      struct ListNode* test = malloc(sizeof(struct ListNode));
      

      另一个相当可爱的选择是使用这种方法:

      struct ListNode* test = malloc(sizeof *test);
      

      这表示“我需要的空间量是test 指向的对象所需的空间量。”正好是sizeof (struct ListNode),用第二种方法就不用打类型了。

      请注意,您遇到的错误是 runtime 错误,而不是 compiler 错误。您拥有的代码是合法的 C 代码,但在您运行程序时将无法正常工作。

      【讨论】:

      • 代码导致未定义的行为,无需诊断。所以“合法”可能不是正确的术语(此类别还包括调用您声明但未定义的函数)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多