Alex Rivera | Logout

C - Malloc and memcpy (memory management)

Asked 2011-10-08T17:11:18.120
8

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.

Edit
Report

1 Answer

1

Notice void *data is a pointer, in data_create, you didn't allocate space for it, you just make it point to a string constant "1234567890a" which is read only.

In main, you create another string constant "123456a", then you make void *data point to the string constant, which is read only.

So when you call memcpy to write to memory address which is not writeable(or without initialized), you got an error.

answered 2011-10-08T17:17:38.163

Your Answer