Search code examples
cpointersmemcpy

Is it legal to pass pointer without length as a destination into memcpy?


I would like to know can I use char pointer without length as a destination in memcpy. Example: I want to copy data from char array of defined length, with certain size into another array, but I would like to define it as a pointer without certain size.

char * ptr_1;
char arr[4] = "Data";
memcpy(ptr_1, arr, 4); // IS it allowed to do this?

Solution

  • ptr_1 is a pointer and pointing to anything and doing memcopy on random location leads to undefined behavior.

    pointer must be assigned to a valid address before memcopy is called.

    Like this,

    char buf[5];
    char * ptr_1 = buf;
    char arr[5] = "Data";
    memcpy(ptr_1, arr, 5); //As string is null terminted need to conside `/0` char as well 
    

    enter image description here