I define a struct type as follows:
typedef struct {
int obs_flag;
double obs_timestamp;
int event_mask;
char *event_name;
char *filedir;
} structdata;
where I have a pointer named obs_data:
structdata *obs_data;
then I want to assign each object of the obs_data as follows:
int observer_flag = 1; double ctime = 2309212380.323100; struct inotify_event* event = (struct inotify_event*)(buffer + bytesProcessed); obs_data->obs_flag = observer_flag; obs_data->obs_timestamp = ctime; obs_data->event_mask = event->mask; obs_data->event_name = event->name; obs_data->filedir = "./myDir/";
in the above, event is a struct from the inotify that captures the events associated with changes to a file or directory in Linux.
when I run the above chunk of code in my program I encounter the Segmentation fault (core dumped).
I am not a pro working with stucts and pointers. Any help is greatly appreciated.
Advertisement
Answer
Your obs_data is just a pointer!! It’s not an instance of structdata. If you want it to be a pointer, you need to malloc memory to hold the struct.
So before using obs_data you need code like:
obs_data = malloc(sizeof *obs_data); // Allocate memory for 1 instance of structdata
if (obs_data == NULL)
{
// allocation failed
exit(1);
}
// Now you can assign values like
obs_data->obs_flag = observer_flag;
...
...
and once you are done using it, remember to free the memory like
free(obs_data);