memcpy(data->data,"123456a",strlen("1234567890a")+1);
fails because the type data->data a void * points to some kind of garbage / invalid address that is not allocated. data has the address of the string literal that is stored in the readonly section (for example, in the .rodata executable file and loaded into memory, which is impossible for writing. In addition, if you did not assign such a string address to the pointer variable, then it will contain some invalid / value of the garbage address that is not allocated or initialized by any valid permitted location, so first select the buffer.
data->data = malloc (sizeof (char) * size);
malloc will return the first address block location address from atleast size * sizeof (char) bytes. Now you can copy size bytes to this memory location that data->data points to.
Remember to free the allocated memory block when you are finished working with this memory block by calling free (addr) .
I see that you tried to allocate the data buffer in a very strange way (?):
struct data_t *dt=malloc(sizeof(struct data_t)+size);
for which additional allocated size bytes along with struct data_t . But be that as it may, the data component still points to a place that cannot be changed. Please, use:
struct data_t *dt = malloc(sizeof(struct data_t)); dt->data = malloc (sizeof (char) * size); memcpy (data->data, "whatever", sizeof ("whatever")+1); return dt;
to free first:
free (dt->data);
then
free (dt);
phoxis
source share