Fen
Fen

Reputation: 37

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?

Upvotes: 1

Views: 681

Answers (2)

TruthSeeker
TruthSeeker

Reputation: 1579

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

Upvotes: 3

Inian
Inian

Reputation: 85720

No, you can't do that. If you do that, it would invoke undefined behavior as the address pointed by ptr_1 is in determinant and you don't own it. Moreover, you haven't allocated any memory to hold the contents from arr.

You can either allocate a static storage for copying the result or allocate a storage dynamically. The prototype for memcpy() is

void *memcpy( void *dst, void const *src, size_t length );

So for a statically allocated address, you can do something like

#include <stdio.h>

int main(void) {
    char temp[5];
    char values[] = "Data";
    memcpy( temp, values, 4 );
    temp[4] = '\0';
    printf("%s\n", temp);
    return 0;
}

or with a dynamically allocated storage location pointed by ptr capable of holding 4 char bytes

#include <stdio.h>
#include <stdlib.h>

#define SIZE 4

int main(void) {
    char *ptr;
    char values[] = "Data";
    ptr = malloc(sizeof(char) * (SIZE+1)); 
    if ( ptr == NULL ) return; 
    memcpy(ptr, values, SIZE);
    ptr[SIZE] = '\0';
    printf("%s\n", ptr);
    return 0;
}

Though the prototype for memcpy() defines the use of void * for the source and destination types, the C standard does not mandate it. Pointers can be converted between any type to void * and vice versa. That is the reason why we don't case the result of malloc() also.

You always need to allocate storage to include a null character at the end. If you initialize the array with a empty length specifier, i.e. as values[], the compiler automatically allocates storage to include a null character at the end. For a library function like printf() to print a string, it would ideally expect the string to be terminated with the null character at the end. Absence of it might trigger undefined behavior as it doesn't know where the end of string is ( the null character). So in the both the cases ensure the last byte of the string is the null character constant.

Upvotes: 4

Related Questions