Reputation: 27
I'm starting learning fundamentals of C, and I got stuck with this simple program which produce this strange output. What I'm trying to do is to copy the content of an array into another array with the memcpy() function.
#include <stdio.h>
#include <string.h>
int main()
{
char source[13] = "Hello, World!";
char destination[13];
memcpy(&destination, &source, 13);
printf("%s\n", destination);
return 0;
}
The "strange" output is:
Hello, World!Hello, World!(
What makes me wondering why it's happening, is that if I change, in memcpy, from 13 to 12 the output is right, obviously without the last char:
Hello, World
So, my question is: "What I am missing? Is there some theoretical fundamental I don't know?"
Upvotes: 0
Views: 356
Reputation: 310990
The conversion specifier %s
serves to output strings that is a sequences of characters terminated by the zero character '\0'
.
However this array
char source[13] = "Hello, World!";
does not contain a string because it has only 13 elements. So it has no space for the terminating zero of the used string literal as an initilaizer.
To to output the array you need to use another format
printf("%.*s\n", 13, destination);
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
int main()
{
enum { N = 13 };
char source[N] = "Hello, World!";
char destination[N];
memcpy( destination, source, N );
printf( "%.*s\n", N, destination );
return 0;
}
Its output is
Hello, World!
Alternatively you could define the arrays as having 14 elements with one element reserved for the terminating zero.
Pay into account that it will be correct to use the following arguments in the call of memcpy
memcpy( destination, source, 13 );
Upvotes: 2
Reputation: 44250
#include <stdio.h>
#include <string.h>
int main()
{
char source[] = "Hello, World!"; // <<-- let the compiler do the counting
char destination[sizeof source]; // <<-- let the compiler do the counting
strcpy(destination, source);
/* equivalent to:
memcpy(destination, source, sizeof source);
*/
printf("%s\n", destination);
return 0;
}
Upvotes: 0
Reputation: 67546
Every string in C needs terminating zero. So the length of your array in too small to accommodate the string and the program invokes the UB.
Change to:
#include <stdio.h>
#include <string.h>
int main()
{
char source[14] = "Hello, World!";
char destination[14];
memcpy(&destination, &source, 14);
printf("%s\n", destination);
return 0;
}
Upvotes: 0