I have the following code:
struct message_t *msg = ( struct message_t* ) malloc ( sizeof( struct message_t ) );
struct server_t *server = ( struct server_t* ) malloc ( sizeof( struct server_t ) );
server = network_connect( argv[ 2 ] );
The function network_connect return a struct server_t. However I contentiously get the error:
warning: assignment makes pointer from integer without a cast [enabled by default].
I don’t understand this error… first I didn’t allocated memory to my pointer server_t. Well I get the error and try allocate memory and nothing. I review the code network_connect and all is right.
My psychic powers tell me that you’re missing the function prototype (declaration) for the
network_connectfunction—make sure to include the header file that it’s contained in.In C, the compiler allows implicit declarations: when the compiler sees a new function name it’s never seen before (such as
network_connect), it assumes that it takes an arbitrary number and types of arguments and that it returnsint. So, due to the implicit function declaration, the compiler thinks you’re trying to convert from anintto astruct server_t*, which results in the given warning.You also have a memory leak in your code—you’re allocating memory for the
serverobject withmalloc, and then you immediately overwrite that pointer with the value returned bynetwork_connect, so that memory you allocated is gone forever. There’s no need to allocate any memory in this case, sincenetwork_connectdirectly returns its value.Finally, in C, there’s no need to cast the return value of
malloc.mallocreturns avoid*, and C (but not C++) allows an implicit cast fromvoid*to any other pointer type. A cast here is just unnecessary extra verbosity, and it can actually hide errors—if you forget to include<stdlib.h>, then any use ofmallocwill use an implicit declaration (see above) that returnsint. A cast will hide the error (that you forgot to include<stdlib.h>), whereas having no cast will give you a warning.