C char* printf issue

Advertisements

I am facing a strange behavior with a char* variable

user_message* parseMessage(char *incoming_msg, uint64_t size)
{
    user_message* msg = calloc(1, sizeof(user_message));
    printf("value: %s\n", incoming_msg);
    return msg;
}
void start_server()
{
    char* msg = "1|david|pwd|";
    printf("msg: %s\n", msg);
    parseMessage(&msg, 12);
}

The output :

msg: 1|david|pwd|
value: �[

I struggle to figure out what is wrong in my code.

>Solution :

The first parameter of the function parseMessage and the expression used as an argument for this parameter have different types.

The parameter is declared as having the type char *

user_message* parseMessage(char *incoming_msg, uint64_t size)

while the expression used as an argument has the type char **.

char* msg = "1|david|pwd|";
//...
parseMessage(&msg, 12);

So in fact instead of outputting the string pointed to by the pointer msg you are trying to output as a string what is stored in memory occupied by the variable msg and what is followed it

You need to call the function at least like

parseMessage( msg, 12 );

Also it would be better at least to declare the first function parameter with the qualifier const if the passed string is not changed within the function

user_message* parseMessage( const char *incoming_msg, uint64_t size);

Leave a ReplyCancel reply