简体   繁体   中英

Using memcpy with hex values

I can do

memcpy(buffer, "\0", 1);

but I can't do

memcpy(buffer, 0x0, 1);

It causes segmentation fault.

Is there a way I can use hex values with memcpy without their string representation?

memcpy accepts two pointers. "\\0" is a pointer to a string. 0x0 interpreted as a pointer is NULL , which is illegal to read and write from on most platforms.

The correct way to rewrite the second example would be to use a pointer:

int x = 0x0;
memcpy(buffer, &x, 1);

Those are very different things.

The first

memcpy(buffer, "\0", 1);

copies 1 character of the literal string "\\0" into buffer .

The second

memcpy(buffer, 0x0, 1);

attempts to copy one byte from 0 . This is the same as

memcpy(buffer, NULL, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM