Why do I get a warning every time I use malloc?

后端 未结 5 748
情话喂你
情话喂你 2020-11-28 06:01

If I use malloc in my code:

int *x = malloc(sizeof(int));

I get this warning from gcc:

new.c:7: w         


        
5条回答
  •  庸人自扰
    2020-11-28 06:28

    You need to add:

    #include 
    

    This file includes the declaration for the built-in function malloc. If you don't do that, the compiler thinks you want to define your own function named malloc and it warns you because:

    1. You don't explicitly declare it and
    2. There already is a built-in function by that name which has a different signature than the one that was implicitly declared (when a function is declared implicitly, its return and argument types are assumed to be int, which isn't compatible with the built-in malloc, which takes a size_t and returns a void*).

提交回复
热议问题