dimitris93
dimitris93

Reputation: 4273

Malloc C and C++ code compatibility

I have made a program that contains the following function in C:

void *e_malloc(size_t size)
{
    void *m = malloc(size);

    if (!m)
    {
        printf("Out of memory, fatal error.");
        abort();
    }

    return m;
}

I am using this as an error free malloc that exits the program when out of memory. The thing is, that when I compile the code in linux with g++, I get an error because it says that it needs to be casted, and as you can see I always return a void pointer cause that's what malloc returns (gcc of course compiles fine). Is there a way I could modify this function to make it work on both compilers ? Do I just have to cast it every time ? Are there other options to make what I am trying to do ?

Also, when I use Cmake (through Clion IDE) the code compiles just fine with "-std=C++11". Why is that ?

1

Upvotes: 0

Views: 416

Answers (3)

You could make it easier to use with macros:

#define e_new(type) ((type*)malloc(sizeof(type)))
#define e_new_array(type, count) ((type*)malloc((count)*sizeof(type)))

example usage:

graph_t *g = e_new(graph_t);
graph_t *ten_gs = e_new_array(graph_t, 10);

Note that this is not specific to your e_malloc - malloc itself has the same problem in C++.

Upvotes: 3

SergeyA
SergeyA

Reputation: 62583

You should not be using this construct in C++ at all. In C++, you need to use new, not malloc - and new already throws an exception (by default). Problem solved.

Upvotes: 0

Adam
Adam

Reputation: 17339

As the compiler error clearly states, the error is in your calling code, not in your e_malloc.

You probably have something like this:

graph_t *g;
g = e_malloc(sizeof(graph_t));

The error is the type conversion between the void * returned by e_malloc and the expected graph_t*. Regular malloc shows the same behavior. You need to do the typecast explicitly:

g = (graph_t*)e_malloc(sizeof(graph_t));

Upvotes: 2

Related Questions