Home > Net >  C char* printf issue
C char* printf issue

Time:12-21

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.

CodePudding user response:

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);

CodePudding user response:

parseMessage(&msg, 12); should be parseMessage(msg, 12);

The &msg means you're passing a pointer to msg, which will be a char ** when the function takes only a char *

CodePudding user response:

&msg yields a char **, or a pointer-to-pointer-to-char.

Both your parseMessage function, and the printf specifier %s expect a char *.

You don't need the address-of operator here

parseMessage(msg, 12);
  • Related