【问题标题】:Warning: implicit declaration of function ‘malloc’, even if <stdlib.h> is included警告:函数“malloc”的隐式声明,即使包含 <stdlib.h>
【发布时间】:2020-09-01 17:01:56
【问题描述】:

这是一段代码的摘录,我用数组的元素填充了一个列表。

#include <stdlib.h>
#include <stdio.h>
#include "../../lib/kernel/list.h"
#include "./listpop.h"

struct item {
    struct list_elem elem;
    int value;
    int priority;
};

void populate(struct list * l, int * a, int n);

void populate(struct list * l, int * a, int n)
{
  int i = 0;
  while(i != n) {
    struct item * newitem = malloc(sizeof(struct item));
    newitem->value = a[i];
    list_push_back(l,newitem);
    i++;
  }
}

void test_assignment_1()
{   struct list our_list;
    list_init(&our_list);
    populate(&our_list, ITEMARRAY, ITEMCOUNT);
}

list.h 中的代码:

/* List element. */
struct list_elem 
{
  struct list_elem *prev;     /* Previous list element. */
  struct list_elem *next;     /* Next list element. */
};

/* List. */
struct list 
{
  struct list_elem head;      /* List head. */
  struct list_elem tail;      /* List tail. */
};

void list_init (struct list *);

list.c 中的代码:

/* Initializes LIST as an empty list. */
void
list_init (struct list *list)
{
  ASSERT (list != NULL);
  list->head.prev = NULL;
  list->head.next = &list->tail;
  list->tail.prev = &list->head;
  list->tail.next = NULL;
}

最后,listpop.h 中的代码:

#define ITEMCOUNT 10
int ITEMARRAY[ITEMCOUNT] = {3,1,4,2,7,6,9,5,8,3};

这是我收到的警告:

warning: implicit declaration of function ‘malloc’

warning: incompatible implicit declaration of built-in function ‘malloc’

到目前为止,我所读到的关于这些警告的所有内容都是添加 stdlib.h,但正如您从我的代码中看到的那样,我已经完成了它,并且代码仍然给我这些警告。我已经多次重新启动代码,所以错误出现在代码的某个地方。

有人知道这里有什么不工作吗?

【问题讨论】:

  • 请在您的问题中包含minimal reproducible example。我没有收到这些警告,但在未声明的类型struct list_elem 上确实收到了错误消息。错误很可能出现在您没有向我们展示的代码中。
  • 您是否从more trivial example 得到同样的错误?
  • 你能说出你正在使用的编译器和版本吗?
  • 您在编译前保存了文件吗?这是文件中的确切代码吗?因为它不应该像你描述的那样表现。
  • 大家,我已经更新了这个问题,提供了有关代码的更多详细信息。问我是否还需要什么。关于编译器的版本,遗憾的是我不知道如何检索它。

标签: c list malloc


【解决方案1】:

您可能正在使用不符合标准的编译器和/或 C 库在过时的系统上进行编译。尝试在 &lt;stdlib.h&gt; 之外包含 &lt;malloc.h&gt; 始终首先包含标准标头。

【讨论】:

  • 我在开头的代码中添加了#include &lt;malloc.h&gt;,但它给了我一个错误。
  • @Kyle:好的,不是正确的解释。您是否在其他包含之前移动了 #include &lt;stdlib.h&gt; 和其他标准标头?
  • 是的,它仍然给我一个 错误。我在虚拟机上运行代码。这可能是问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多