1

I'm working on a project in which I have a header which defines list and list_elem structures much like the actual c libraries(the implementation of lists has no bugs). I'm writing a source file which uses the list implementation and I receive the following warning:

warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]

This is the declaration of the list_elem structure

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

Which I use here:

//creates a list element
struct list_elem le_current;
&le_current = (struct list_elem *)malloc(sizeof(struct list_elem));

I know there is another question with the same issue, but unlike that person, I did include

#include <stdlib.h>

and also the header which defines the lists

#include "lib/kernel/list.h"
bsky
  • 19,326
  • 49
  • 155
  • 270
  • 2
    Of interest might be "dont cast malloc thread"- http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Jimbo Feb 07 '14 at 16:43
  • don't cast malloc most likely – Moonhead Feb 07 '14 at 16:44
  • 3
    The implicit declaration implies that the compiler has not seen a declaration for `malloc`... is `stdlib.h` defo being included before this statement? (I know you said you did but might be worth a double check). – Jimbo Feb 07 '14 at 16:46
  • 6
    Surely "&le_current" isn't valid on the left hand side of an assignment? I suspect there's more going on than we've been told/shown. – Nigel Harper Feb 07 '14 at 16:47
  • 2
    Does `le_current` need `malloc`ing? – doctorlove Feb 07 '14 at 16:48
  • @Nigel: Good spot +1... yes that won't help. The decl should have been `struct list_elem *le_current; le_current = ...` – Jimbo Feb 07 '14 at 16:48

1 Answers1

6

It is virtually certain that <stdlib.h> is not included before the code that gets the compiler warning message that malloc is being implicitly declared. You should look for the following situations:

  • #include <stdlib.h> appears in conditional code (due to preprocessor statements such as #if, #elif, or #else) and is not actually included.
  • The line getting the warning is earlier than the line that includes <stdlib.h>.
  • You are not compiling the source file you think you are.
  • You have not saved the contents of an editor’s buffer to disk, so the version of the file that is being compiled is an old one, not the one you are viewing in an editor.
  • Before <stdlib.h> is included, there is a #define that replaces malloc with something else (and likely an #undef after <stdlib.h> is included. (This is rare but possible.)

If these do not reveal the error, you should reduce the problem to a short, self-contained compilable example. The exercise of doing so will most likely illuminate the problem.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312