0
#define MALLOC(p,s)\
if(!(p=malloc(s)))\
    printf("Not enough memory");
#define MALLOC(ptr,s)\
if(!(ptr=malloc(s)))\
    std::cout<<"Not enough memory";

This runs perfectly in c but in cpp it throws error int* cannot be converted to void*

  • 3
    You misquoted the error. See [Why does C++ require a cast for malloc() but C doesn't?](https://stackoverflow.com/questions/3477741/why-does-c-require-a-cast-for-malloc-but-c-doesnt) – dxiv Oct 21 '20 at 04:33
  • 1
    Very BAD macro. Never do it! `if (!p) MALLOC(p, 10) else printf("p already assigned\n");` – 273K Oct 21 '20 at 04:41

1 Answers1

3

It is the other way around: void* cannot be converted to int* in C++ - unlike in C.

malloc returns void*, and apparently you invoke this macro with int* ptr. You can make the 2nd macro compiled in C++ in this particular case by adding a cast:

#define MALLOC(ptr,s)\
if(!(ptr=static_cast<int*>(malloc(s))))\
    std::cout<<"Not enough memory";

Or more general (starting from C++11):

#define MALLOC(ptr,s)\
if(!(ptr=static_cast<decltype(ptr)>(malloc(s))))\
    std::cout<<"Not enough memory";

Of course, idiomatic C++ does not use malloc() at all.

Eugene
  • 6,194
  • 1
  • 20
  • 31