tags:

views:

60

answers:

2

In C, what will happen if I supply a signed integer especifically a negative integer as the 3rd argument to the memcpy function?

Example:

 memcpy(destBuf, source, -100*sizeof(source))

Will the result of -100*sizeof(source) be interpreted by memcpy as unsigned?

Thanks!

+6  A: 

the last parameter is unsigned. so by doing -100 * sizeof( source ) you'll get a huge number (That will wrap around, ie overflow).

This is equivalent to doing "4,294,967,196 * sizeof( source )".

Edit: Actually thats wrong I just realised. It will do -100 * sizeof( source ) and then convert it to an unsigned. For example if sizeof( source ) is 4 then it will convert -400 to unsigned and give you 0xFFFFFE70 (4,294,966,896).

Goz
What will happen if their product gets so big for an unsigned integer?
ultrajohn
It will wrap around. ie 0xFFFFFFFF + 0x1 = 0x00000000
Goz
Specifically, it'll convert it to `size_t`, so that value will convert to `SIZE_MAX + 1 - 100 * sizeof(source)`.
caf
+2  A: 

No, you will copy a big amount of data since -100 seen as an unsigned number is a huge unsigned number, something like FFFFFF9C, which is 4 billions or so... the fact that you are multiplying it to sizeof(source) may reduce it a bit ...

ShinTakezou