Reputation: 534
I am looking to set the result of an expression(which is an int) into an int pointer. If I do the following:
int* a = new int;
memcpy(a, (int*)(3+4), sizeof(int));
I'm having trouble wrapping my head around it's expected behavior. Wll it copy the value 7 into a as expected. Or will it cause some undefined behavior
Upvotes: 0
Views: 42
Reputation: 372814
Nope, this won’t copy the value 7 in there. Instead, you get undefined behavior.
Think of writing memcpy(dest, source, size)
as saying “please go to the memory address specified by source
and copy size
bytes from it. If you write (int *)(3 + 4)
, you get a pointer whose numeric value is seven, meaning that it points to memory address 7. Just as you wouldn’t expect house 137 on a block to be inhabited by people named Mr. and Mrs. 137, you shouldn’t expect the contents of memory address 7 to be the numeric value 7.
In fact, memory address 7 is unlikely to even be storage you can read or write from. You essentially “made up” an address with the typecast, and there’s no reason to believe there’s anything meaningful there. Imagine writing down a fake mailing address on a letter and dropping it in the mail. The odds that it actually reaches anyone is slim, and if it does reach them they’ll have no idea why you’re contacting them.
From a language perspective, this is undefined behavior, and on most systems it’ll segfault.
Upvotes: 3