James Higgins James Higgins - 6 months ago 27
C++ Question

What is wrong with this snippet of code

Guys I am new to programming and was just playing around with some functions, I wanted to test the

function but my code simply just breaks without actually throwing an error, could you please help me out and tell me what I am doing wrong?

int main()
char *psz = "Hello world!";
char dst[1024];

memcpy(psz, dst, sizeof(psz));

return 0;


Your first two parameter values of memcpy() are backwards. The first parameter of memcpy() is the destination, the second parameter is the source. You are trying to copy a local (uninitialized) buffer into the memory of a string literal. A string literal is stored in read-only memory, which is why you are getting a runtime error.

Also, your use a sizeof() is wrong, too. psz is declared as a pointer. The size of a pointer is 4 bytes on a 32bit system, and 8 bytes on a 64bit system. If you reverse your buffer parameters, on a 32bit system you would copy Hell, and on a 64bit system you would copy Hello wo.

I suspect you intended to do the following instead:

memcpy(dst, psz, strlen(psz)+1);

Or maybe:

char psz[] = "Hello world!";
char dst[1024];

memcpy(dst, psz, sizeof(psz));