I'm a bit new to C and I'm having trouble understanding how memory works, especially in-built functions like memcpy.
Here's a struct I'm using
struct data_t {
int datasize;
void *data;
};
And here's an auxiliary function that I'm using it with:
struct data_t *data_create(int size)
{
struct data_t *dt=malloc(sizeof(struct data_t)+size);
dt->datasize=size;
dt->data="1234567890a";
return dt;
}
Now in the main function I have no problem doing this:
struct data_t *data = data_create(1024);
data->data="123456a";//just an example
But this throws a Seg Fault:
memcpy(data->data,"123456a",strlen("1234567890a")+1);
My question is why? And how do I avoid it? Please bear in mind I'm new to C so how C deals with memory is a bit new to me
Thank you.
Edit: It works! Thank you very much. Completly missed the data pointer. Now everything is working fine according to valgrind.