Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set number of bytes with memcpy?

I read about the heartbleed exploit and that is was mistake with memcpy.

void * memcpy( void * dest, const void *src, size_t len );

A proper call to memcpy can look like this

int a[4711] [4711];
 int b[4711] [4711];
/* initialize a */
(void) memcpy( &b [0] [0], &a [0] [0], sizeof( a ) );

But why the third parameter, when would that be different from the size of the src? I've seen other examples where it's the dest size that is used, when should that be done?

like image 736
Niklas Rosencrantz Avatar asked Jan 23 '26 00:01

Niklas Rosencrantz


1 Answers

If you take a look a the the memcpy Man page, the third argument is the number of bytes that is copied from src to dst. So it doesn't matter if you use the size of src or size of dst. But you must ensure that the source and destination buffer sizes are at least equal or greater than the number of bytes copied. Otherwise, buffer overflow will occur.

like image 160
tonga Avatar answered Jan 24 '26 17:01

tonga