So I'm trying to store a response from a libcURL HTTP request into a C-string to be parsed later on. The response code is written entirely in C, while everything else is in C++, and with any other C++ compiler, it should work fine. But when I try to compile, even if I give the '-x c' arguments followed by the filename, I get these specific responses.
g++ main.cpp -x c cJSON.c -x c respbuffer.c -lcurl -lm
./respbuffer.c:14:9: error: assigning to 'char *' from incompatible type 'void *'
s->ptr = malloc(s->len+1);
^ ~~~~~~~~~~~~~~~~
./respbuffer.c:23:9: error: assigning to 'char *' from incompatible type 'void *'
s->ptr = realloc(s->ptr, new_len+1);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
Weirdly enough, this error only pops up when compiling with g++. If I use gcc, it works fine, and it runs smoothly enough. For the curious, I wrote everything in Xcode, and I'm compiling with GCC 4.2.1.
This happens because C is pretty laxed with types, while C++ is strict. malloc() returns void*, so in order to use it as char* you need to cast it.
You should not use a C++ compiler to compile C code. The two languages are different, and code which is correct in C may silently misbehave in C++.
Adding a cast to your code masks the problem; even if it appears to work for now, you really have no idea what else might be happening.
On my system, -x c
causes g++
to actually invoke the C compiler. Perhaps you have some version of g++ that does not support that switch, or perhaps g++
is an alias for some other compiler on your system.
If you cannot get -x c
to work, then use gcc
as the compiler instead of g++
. (You will need to use separate invocations for the C files than for the C++ files, followed by a link step).
In C the malloc
function return a void*
of a memory block on the heap. In C it's everything ok because a void*
is implicitly casted to a char*
.
But in C++ it's forbidden, so you have to explicitly cast it.
So in this case the right code is:
s->ptr = static_cast<char*>(malloc(s->len+1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With