In this code:
void reserve(int length, void *context_data ,void *buffer)
{
context_data = (char *) malloc(length);
memcpy(context_data, buffer, length);
}
The context_data
parameter is passed by value, so context_data
inside of reserve
and context_data
outside of reserve
aren't the same pointer. Consequently, when you reassign context_data
locally inside this function, the context_data
pointer in main
isn't updated, causing the crash.
To fix this, either take in a pointer to the context_data
variable to update, like this:
void reserve(int length, void **context_data ,void *buffer)
{
*context_data = malloc(length);
memcpy(*context_data, buffer, length);
}
reserve(length, &context_data, buffer);
Or, alternatively, have reserve
return the updated pointer:
void* reserve(int length,void *buffer)
{
void* context_data = (char *) malloc(length);
memcpy(context_data, buffer, length);
return context_data;
}
void* context_data = reserve(length, buffer);
Hope this helps!