Mickey
Mickey

Reputation: 127

C - What's wrong with using malloc like this?

typedef struct node node;

//  LinkedList data structure to hold characters.
struct node {
    char character;
    node *link;
};

Later I try:

node *tmp = malloc(sizeof (node));

And I get an error in my text editor saying:

clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated
error: cannot initialize a variable of type 'node *' with an rvalue of type 'void *'
            node *tmp = malloc(sizeof (node));
                  ^     ~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    [Finished in 0.1s with exit code 1]

I get the same error in Xcode, but it works and compiles fine using gcc in Terminal. How come?

Thanks in advance.

Upvotes: 3

Views: 924

Answers (1)

Xephon
Xephon

Reputation: 393

malloc returns type void *. What you want is to cast a raw buffer region of void * to node *.

By adding (node*) cast before malloc, you are using C style cast. In GCC, the compiler will auto match un-casted memory to node*. This is not a standard behavior for C++ compilers though. At the same time, if you turn on warnings by add -Wall option, you should see a warning for the missed cast.

CLang is little more strict than GCC when it comes to this. It basically dose not allow anything not within standard and Apple derived standards.

To properly fix this, you need to

  1. add (node *) cast before malloc
  2. wrap the whole code body with extern "C" { ... } clause.
  3. use #ifdef to determine if the compiler is c++ compiler if desired.

This will ensure that compiler understand that the code is c code and the type cast will be performed properly.

Upvotes: 1

Related Questions