[英]Why is memcpy seg faulting?
So I know that the following code can use '=' and be much easier and better, but I'm trying to understand memcpy better for more complex applications. 因此,我知道以下代码可以使用'='并且变得更容易和更好,但是我试图为更复杂的应用程序更好地理解memcpy。 When I use "ptr = b", i get an output of "1", which is what I expect.
当我使用“ ptr = b”时,得到的输出为“ 1”,这是我期望的。 In using memcpy, it segfaults.
在使用memcpy时,它会出现段错误。
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int *b = &a;
void* ptr;
memcpy(ptr, b, sizeof(b));
int *c = (int *)ptr;
cout<<*c<<endl;
return 0;
}
ptr
does not point to anything, so attemp to change data it points to leads to crash. ptr
不会指向任何内容,因此尝试更改它指向的数据会导致崩溃。
You probably want to do memcpy(&ptr, &b, sizeof(b));
您可能想做
memcpy(&ptr, &b, sizeof(b));
(Change value of ptr
itself) (更改
ptr
本身的值)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.