memcpy function issue when multiple times used

78 views Asked by At
// 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.

Data : HI
 
Data : HI CMDCMD
 
Data : HI
MDCMD

last printf get extra \r\n

2

There are 2 answers

2
MikeCAT On BEST ANSWER
  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;
}
2
julaine On

Your code has two issues:

(1) data does not point to anything, you need to make it point to valid memory first (for example, using malloc). memcpy expects the memory-location of its source and destination to be valid - it does not return you a new memory-location, it works with the pointers you give them and does not modify them.

(2) When you copy a string in C, you need to make sure to also include the null-termination with the \0-character. You do not just want to copy 'H', 'I', '\r' and '\n' to the destination, but also '\0'. That is five bytes, not four.