Reputation: 1088
I'm trying to get my own version of memcpy to copy a character array from one pointer to another. However, this gives an error. It seems like there is an issue with printf.
Secondly, the official memcpy function returns the destination pointer. Is that really required? If I modify *dest, it should be reflected in *d anyway. So what is the need to return anything?
#include <stdio.h>
void memcpy2(void *dest, const void *src, size_t n)
{
char *dp = dest;
const char *sp = src;
while (n--)
*dp++ = *sp++;
}
int main(void) {
char *c = "Hello";
char *d=NULL;
memcpy2(d,c,3);
printf( "%c", *d);
return 0;
}
Upvotes: 0
Views: 1502
Reputation: 53006
You dereference a NULL
pointer that's undefined behavior, you should allocate space and point to it with d
in order for that to work, do this, instead of
d = NULL
write
d = malloc(3);
and don't forget
free(d);
after the printf()
.
If you want to automagically make d
a valid pointer then write memcpy2()
this way
void memcpy2(void **dest, const void *src, size_t n)
{
*dest = NULL;
if ((src == NULL) || (n == 0))
return;
*dest = malloc(n);
if (*dest == NULL)
return;
char *dp = *dest;
const char *sp = src;
while (n--)
*dp++ = *sp++;
}
and then your main would be
int main(void) {
char *c = "Hello";
char *d = NULL;
memcpy2(&d, c, 3);
/* ^ pass the address of the pointer, so you can change where it points to */
if (d != NULL) /* prevent NULL dereference. */
{
printf("%c", *d);
free(d);
}
return 0;
}
Upvotes: 5