Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 这是什么原因造成的;存储地址空间不足”;错误_C_Pointers_Malloc_Sizeof - Fatal编程技术网

C 这是什么原因造成的;存储地址空间不足”;错误

C 这是什么原因造成的;存储地址空间不足”;错误,c,pointers,malloc,sizeof,C,Pointers,Malloc,Sizeof,此时,我应该收到一个填充的结构。相反,我得到的是: struct ListNode { int val; struct ListNode *next; }; struct ListNode* test = malloc(sizeof(struct ListNode*)); test->val = 6; struct ListNode* lex = malloc(sizeof(struct ListNode*));

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

    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;

这是怎么回事?

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


try:
struct ListNode*test=malloc(sizeof(struct ListNode))

让我们看看这行代码:

   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
指针
test
想要指向一个足够大的内存块,以容纳一个实际的、诚实的
struct ListNode
对象。该对象中有一个整数和一个指针

但是,您对
malloc
的调用会显示“请给我足够的空间来存储指向
struct ListNode
对象的指针”。内存不足,无法容纳
struct ListNode
,因此出现了错误

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

struct ListNode* test = malloc(sizeof(struct ListNode*));
另一个相当可爱的选择是使用这种方法:

struct ListNode* test = malloc(sizeof(struct ListNode));
这表示“我需要的空间量是
test
指向的对象需要的空间量。”这正好是
sizeof(struct ListNode)
,不需要使用第二种方法键入类型


请注意,您得到的错误是运行时错误,而不是编译器错误。您拥有的代码是合法的C代码,但在运行程序时不起作用。

该代码导致未定义的行为,无需诊断。因此,“legal”可能不是正确的术语(该类别还包括调用您声明但未定义的函数)
struct ListNode* test = malloc(sizeof *test);