简体   繁体   English

C-这样使用malloc有什么问题?

[英]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. 我在Xcode中遇到了同样的错误,但是在Terminal中使用gcc可以正常工作并且编译良好。 How come? 怎么会?

Thanks in advance. 提前致谢。

malloc returns type void *. malloc返回类型void *。 What you want is to cast a raw buffer region of void * to node *. 您想要的是将void *的原始缓冲区区域转换为节点*。

By adding (node*) cast before malloc , you are using C style cast. 通过在malloc之前添加(node*) malloc ,您正在使用C样式强制转换。 In GCC, the compiler will auto match un-casted memory to node* . 在GCC中,编译器会将未广播的内存自动匹配到node* This is not a standard behavior for C++ compilers though. 但是,对于C ++编译器而言,这不是标准行为。 At the same time, if you turn on warnings by add -Wall option, you should see a warning for the missed cast. 同时,如果您通过添加-Wall选项打开警告,则应该看到错过的演员的警告。

CLang is little more strict than GCC when it comes to this. 在此方面,CLang比GCC严格得多。 It basically dose not allow anything not within standard and Apple derived standards. 它基本上不允许任何不符合标准和Apple衍生标准的东西。

To properly fix this, you need to 要正确解决此问题,您需要

  1. add (node *) cast before malloc 在malloc之前添加(node *)强制转换
  2. wrap the whole code body with extern "C" { ... } clause. extern "C" { ... }子句包装整个代码体。
  3. use #ifdef to determine if the compiler is c++ compiler if desired. 如果需要,使用#ifdef确定编译器是否为c ++编译器。

This will ensure that compiler understand that the code is c code and the type cast will be performed properly. 这将确保编译器理解该代码是c代码,并且类型转换将正确执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM