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

memcpy function issue when multiple times used

// Powered by Judge0
#include <stdio.h>
#include <string.h>
#include <stdint.h>


typedef struct {
    char data[500];
    uint32_t len;
} payload;

void at_start(payload* payloadData)
{
    char p1[20] = "HI\r\n";
    memcpy(payloadData->data, p1, 4);
    payloadData->len = 4;
}

void at_net(payload* payloadData)
{
    char p1[20] = "HI CMDCMD\r\n";
    memcpy(payloadData->data, p1, 14);
    payloadData->len = 14;
}

int main(void) {

    payload* payloadData;
    at_start(payloadData);
    printf("Data : %s \n", payloadData->data);
    at_net(payloadData);
    printf("Data : %s \n", payloadData->data);
    at_start(payloadData);
    printf("Data : %s \n", payloadData->data);
    

    printf("Hello Judge0!\n");
    return 0;
}

can you help to figure out memcpy function issue when multiple times used and how to used data with dynamic length

issue when used data length was changed based on function.

issue is output got wrong.

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

Data : HI
 
Data : HI CMDCMD
 
Data : HI
MDCMD

last printf get extra \r\n

>Solution :

  1. undefined behavior is invoked by using payloadData without initialization
  2. the len member is not read and data is simply printed until the end of string (null character '\0')

Try this:

int main(void) {
    /* initialize payloadData to a valid pointer */
    payload data;
    payload* payloadData = &data;
    at_start(payloadData);
    /* use %.*s to specify the length to print */
    printf("Data : %.*s \n", payloadData->len, payloadData->data);
    at_net(payloadData);
    printf("Data : %.*s \n", payloadData->len, payloadData->data);
    at_start(payloadData);
    printf("Data : %.*s \n", payloadData->len, payloadData->data);
    

    printf("Hello Judge0!\n");
    return 0;
}
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