Struct | assign struct objects | Segmentation Fault Error - c

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.

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);

Related

copying pointer to a structure in a structure

I am working with the library libusb which is working nicely, but now I am trying to use its structures in a structure of my own. I think the problem is just the way I copy the structures, so there is probably no need to understand how libusb works.
I have my structure containing libusb structures:
struct device {
libusb_device *device_handled;
libusb_device_handle *handle;
int port[7];
};
typedef struct device device;
and my function:
int myfunction(device *device_element)
{
libusb_device *tempdevice;
libusb_device_handle *temphandle;
device_element = malloc(sizeof(device));
//my code here where I use tempdevice and temphandle
(&device_element)->device_handled = tempdevice;
(&device_element)->handle = temphandle;
}
The error issued come from the two last lines and I don't really understand why.
‘device_element’ is a pointer; did you mean to use ‘->’?
(&device_element)->handle = temphandle;
^~
->
you don't need to add & before device_element because malloc returns a pointer to the allocated structure. So just use:
(device_element)->device_handled = tempdevice;
(device_element)->handle = temphandle;
You don't need the & operator there.
Just use
device_element->device_handled = tempdevice;
device_element->handle = temphandle;

How to pass data to kthread_run

I'm try to make simple kernel module with multithreading.
So I'm using linux/kthread.h, kernel v. 5.2.11
Problem: I can't passing the char array into thread: Segmentation fault.
That's what I'm doing:
typedef struct {
int num;
char origin[MAXSTR]; //part of input for current thread
struct completion wait_for_thread; //completion struct
} kthread_arg;
Then:
struct task_struct *task;
static kthread_arg kta_first_thread;
kta_first_thread.num = 1;
strncpy(kta_first_thread.origin, dat1, MAXSTR );
//Here I have normal char array 'origin'
init_completion(&kta_first_thread.wait_for_thread);
task = kthread_run(&thread_function, (void*)&kta_first_thread, "one");
And after that I have the error. Moreover, if you remove the array from struct, then everything works.
I'm sure doing something wrong?
The args passed to kernel_run must be kmalloced, your args is in stack. I have met the same problem, your code should like this:
struct your_struct* test=NULL;
struct task_struct* t=NULL;
test=(struct your_struct*)kmalloc(sizeof(struct your_struct),GFP_KERNEL);
t=kthread_run(your_function,(void*)test,name);

in C programming, is there anyway to get return value of function in child struct(struct in struct)?

I'm trying to return some function in the double struct.
It is always ok when you get return value in single struct structure.
What I'm trying to do is define struct in struct structure. That is, making child struct in parent struct. For example, as seen on the source below, I've made two struct 'Person' and 'Machine', and then I would like to add Person struct under the 'Machine' so that I get double struct structure, which can be used to define machineperson. then would like to get some return value of function in one of struct in parent struct which is machine->person->name..
Everytime I get return in buff->PD, there some error occurs. Of course it's ok I use single struct like Person or Machine, which is not what I intend to do.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct _Person {
char name[20];
int age;
} Person;
typedef struct _Machine {
char address[100];
Person PD ;
} Machine;
Person *GetPersonData(){
Person *pd = (Person*)malloc(sizeof(Person)) ;
strcpy(pd->name, "GETperson");
return pd ;
//free (pd) ;
}
Machine *GetMachineData(){
Machine *md = (Machine*)malloc(sizeof(Machine)) ;
strcpy(md->address, "GETmachine");
return md ;
//free (md) ;
}
Person *GetPDdata(){
Person *pd = (Person*)malloc(sizeof(Person)) ;
strcpy(pd->name, "GOT Machine people");
return pd ;
//free (md) ;
}
int main(){
Person *p1;
Machine *m1 ;
Machine *buff ;
p1 = GetPersonData() ;
m1 = GetMachineData() ;
buff->PD = GetPDdata() ; // Error code
m1->PD.name = buff->PD.name ; // Error code
return 0;
}
buff->PD = GetPDdata() ; // Error code
Here buff is not initialized with any value. you need to allocate buff first
m1->PD.name = buff->PD.name ; // Error code
Here you can not assign strings directly , you need to use strcpy for that
I believe the problem is in the structure definition. Since you want to allocate the person inside the machine directly, I would suggest a different definition for the structure Machine
typedef struct _Machine {
char address[100];
Person *PD ;
} Machine;
Then you only need one function to get the person data. You can remove the function GetPDdata
The function GetMachineData can be modified to get both machine and person data as follows
Machine *GetMachineData(){
Machine *md = (Machine*)malloc(sizeof(Machine)) ;
strcpy(md->address, "GETmachine");
md->PD = GetPersonData();
return md ;
}
The above is the recommended method, but you can also get the machine and person data separately in main.
// keeping GetMachineData unchanged from original question.
int main(){
Machine *buff ;
buff = GetMachineData();
buff->PD = GetPersonData();
}
buff->PD = GetPDdata() ; // Error code
This won't work because GetPDdata() returns a 'pointer' to a Person, not a person itself.
So you need to either do:
buff->PD = *GetPDdata() ; // Error code
to copy from the pointer returned by GetPDdata() (in which case the memory allocation you did becomes kind of pointless).
Or else you could use:
p1 = GetPDdata();
which is fine because p1 is also a pointer to a person.
m1->PD.name = buff->PD.name ; // Error code
The problem here is that you cannot assign one array to another. You have to copy character by character or use something like memcpy.

Allocating memory for struct within a struct in cycle

I'm working on INI-style configuration parser for some project, and I gets next trouble.
I have 3 structures:
typedef struct {
const char* name;
unsigned tract;
int channel;
const char* imitation_type;
} module_config;
typedef struct {
int channel_number;
int isWorking;
int frequency;
int moduleCount;
} channel_config;
typedef struct {
int mode;
module_config* module;
channel_config* channel;
} settings;
And I have function for handling data in my INI-file (I working under inih parser): [pasted to pastebin cause too long]. Finally, in main(), I did the next:
settings* main_settings;
main_settings = (settings*)malloc(sizeof(settings));
main_settings->module = (module_config*)malloc(sizeof(module_config));
main_settings->channel = (channel_config*)malloc(sizeof(channel_config));
if (ini_parse("test.ini", handler, &main_settings) < 0) {
printf("Can't load 'test.ini'\n");
return 1;
}
In result, binary crashes with memory fault. I think (no, I KNOW), what I'm incorrectly allocating the memory in handler(), but I does not understand, where I do it wrong. I spent all night long trying to understand memory allocating, and I'm very tired, but now me simply interestingly, what I'm doing wrong, and HOW to force this working fine.
P.S. Sorry for ugly english
The problem seems to be related to the reallocation of your structs:
pconfig = (settings *) realloc(pconfig, (module_count + channel_count) * sizeof(channel_config));
pconfig->module = (module_config *) realloc(pconfig->module, module_count * sizeof(module_config));
pconfig->channel = (channel_config *) realloc(pconfig->channel, channel_count * sizeof(channel_config));
First of all, you must not reallocate the main settings struct. Since your handler will always be called with the original pconfig value, the reallocation of the module and channel arrays has no effect, and you'll access freed memory.
Also when reallocating the module and channel arrays you should allocate count + 1 elements, since the next invocation of handler might assign to the [count] slot.
So try to replace the three lines above with:
pconfig->module = (module_config *) realloc(pconfig->module, (module_count + 1) * sizeof(module_config));
pconfig->channel = (channel_config *) realloc(pconfig->channel, (channel_count + 1) * sizeof(channel_config));

Malloc Typedef Struct Problems

I am working on building a threads library and for some reason have run into a simple malloc problem that I can't fix right now. I'm sure it's something simple I'm just missing it.
In my main.c I have the following code:
//declare testSem
tasem_t testSem;
int main(int argc, char **argv){
ta_libinit();
//initialize testSem
ta_sem_init(&testSem, 5);
//wait test
ta_sem_wait(&testSem);
the relevant code in my thread library is as follows:
void ta_sem_init(tasem_t *sema, int value)
{
//malloc the semaphore struct
sema = malloc(sizeof(tasem_t));
//error check
if(sema == NULL)
{
printf("could not malloc semaphore");
exit(0);
}
//initialize with the given value
sema->val = value;
printf("SemaVal = %i\n", sema->val);
}
void ta_sem_wait(tasem_t *sema)
{
printf("SemaVal = %i\n", sema->val);
if(sema->val <= 0)
{
//not done yet
printf("SWAPPING\n");
}
else
{
printf("SemaVal = %i\n", sema->val);
sema->val = sema->val + 1;
}
}
Here is the struct from my header file:
//struct to store each semas info
typedef struct tasem_t_struct
{
//value
int val;
//Q* Queue
//int numThreads
}tasem_t;
The output I get from this is:
SemaVal = 5
SemaVal = 0
SWAPPING
So evidently, I'm not mallocing my struct correctly as the value inside is lost once I go out of scope. I know I must just be forgetting something simple. Any ideas?
You can't seem to decide who's responsible for allocating your tasem_t structure. You have a global variable for it and pass its address to ta_sem_init. But then you have ta_sem_init dynamically allocate a brand new tasem_t structure, saving its address to sema, a local function argument, so that address gets lost when it falls out of scope.
Pick one, either:
Make ta_sem_init initialize an existing tasem_t variable.
Make ta_sem_init allocate and initialize a new tasem_t structure and then return its address (either directly or via a tasem_t** output parameter).

Resources