I am trying to run the following program, in which I dynamically allocate memory to a variable using a function called reserve. When I run the application, I get segmentation fault because of allocating the memory in a separate function for an empty pointer, but If I want allocate the memory in the main, I don't get this error. So what am I doing wrong?
Here is the code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct{
unsigned char state;
/* socket fd of the client */
int fd;
/* File path requested by the 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 are 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);
}