Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C char* printf issue

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading