shanjib_
shanjib_

Reputation: 65

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. When I use "ptr = b", i get an output of "1", which is what I expect. In using memcpy, it segfaults.

#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;
}

Upvotes: 1

Views: 93

Answers (1)

Revolver_Ocelot
Revolver_Ocelot

Reputation: 8785

ptr does not point to anything, so attemp to change data it points to leads to crash.

You probably want to do memcpy(&ptr, &b, sizeof(b)); (Change value of ptr itself)

Upvotes: 7

Related Questions