c - Allocating memory using malloc in a function, segmentation fault -
i trying run following program, in dynamically allocate memory variable using function called reserve. when run application, segmentation fault because of allocating memory in separate function empty pointer, if want allocate memory in main, don't error. doing wrong?
here code:
#include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct{ unsigned char state; /* socket fd of client */ int fd; /* file path requested client */ char file_path [255]; /* current file offset */ unsigned long int offset; } state; void reserve(int length, void *context_data ,void *buffer) { context_data = (char *) malloc(length); memcpy(context_data, buffer, length); } int main() { state test; int length = sizeof(state); char buffer[1500]; char *ptr = buffer; test.state = 10; strcpy(test.file_path, "hello how you"); memcpy(ptr, &test, length); ptr += length; char *context_data; reserve(length, context_data, buffer); state *temp = (state *) context_data; printf("file path %s\n", temp->file_path); printf("state %d\n", temp->state); }
in code:
void reserve(int length, void *context_data ,void *buffer) { context_data = (char *) malloc(length); memcpy(context_data, buffer, length); }
the context_data
parameter passed value, context_data
inside of reserve
, context_data
outside of reserve
aren't same pointer. consequently, when reassign context_data
locally inside function, context_data
pointer in main
isn't updated, causing crash.
to fix this, either take in pointer context_data
variable update, 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 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 helps!
Comments
Post a Comment