copying pointer to a structure in a structure - c

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;

Related

C embedded change values of struct from another file

Hello I am working on a small roboter project at uni and I have run into following issue.
I have a typedef called RoboterData inside of a header file because I want to make use of it across multiple files. Inside of the main file I have a RoboterData data variable which holds important data.
My goal is to have access from other files to this data having the ability to get and set it from another file. I want to avoid the use of a global variable.
Here are the relevant code fragments of my approach:
main.h
typedef struct {
DriveMode mode;
short sensor_left;
short sensor_mid;
short sensor_right;
int left_eng_speed;
int right_eng_speed;
} RoboterData;
main.c
# include "motors.h"
// The Data I want to get and set from other files.
RoboterData data;
// Call to a funcion defined in motors.c
drive_straight(RoboterData *data);
motors.h
void drive_straight(RoboterData *data);
motors.c
# include "main.h"
enum {
ENG_STILL = 0,
ENG_SLOW = 50,
ENG_MID = 155,
ENG_FAST = 200
}
void drive_straight(RoboterData *data) {
data ->left_eng_speed = ENG_FAST;
data ->right_eng_speed = ENG_FAST;
set_duty_cycle(LEFT_ENG, ENG_FAST);
set_duty_cycle(RIGHT_ENG, ENG_FAST);
}
When I later try to print out the values left_eng_speed and right_eng_speed via serial port it stays at 0. I know C is call by value but since I am passing a ptr to my struct the value I am passing is the adress of the struct and when I dereference it via '->' I should be able to access its original data from my understanding and not a copy because the only thing I copied was the address.
If someone could explain to me why this is not working and provide a viable alternative, I would be very greatfull.
// Call to a funcion defined in motors.c
drive_straight(RoboterData *data);
This is a function declaration. It doesn't do anything. You want
drive_straight(&data);
to actually call the function.

Hiding implementation details when passing data around

I'm not even sure how to properly formulate question about this.
I'm writing a library where I have multiple implementations (multiple libraries out of one). I want to hide as much as possible, if not all, implementation details from client app, in order to write an app disregarding implementation details.
It's all fine when implementation is contained within one function. However, often I need to instantiate a struct from library, do something to it with a function from library, resume writing app as normal, and then return to a function from library with data from previous function from library.
Struct details are important ONLY to library functions. I don't need to see or touch those from client application apart from passing them around because of this.
So, is there a way to hide struct details from client app and still be able to use it or if there's another way of doing this by some form of encapsulation or maybe even some kind of data (globals?) visible only to library?
Here's my lame illustration example with code:
/*
library_private.h
*/
#if (A)
{
struct mystruct_t {
A *something;
}
}
#else
struct mystruct_t {
B *something;
}
#endif
/*
library_public.h
*/
struct mystruct_t;
/*
library.c
*/
struct mystruct_t* create() {
struct mystruct_t *handle = malloc(sizeof(struct mystruct_t));
return handle;
}
/*
client.h
*/
struct mystruct_t;
/* but, I need a definition, so I have to repeat either from library_private.h */
/*
client.c
*/
int main(int argc, char const *argv[]) {
struct mystruct_t *handle = create();
/*...*/
something(handle);
return 0;
}
Cast to a void * when returning and back to structure mystruct_t just after passing into a function. This is not great as you will loose some of the compiler type checking.
client.c (or client.h) should include library_public.h. There is no need to have the structure definition. Only its declaration struct mystruct_t; is enough to use pointers to the structure. Of course, you cannot access its members, but that is exactly what you want in this case.

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

keyboard interrupt handler giving null value

I am learning Linux Kernel Module programming(Interrupt Handler) and using the tutorial (http://tldp.org/LDP/lkmpg/2.6/html/) exact module link(http://tldp.org/LDP/lkmpg/2.6/html/x1256.html).
In the tutorial I am getting error when I used
INIT_WORK(&task, got_char, &scancode);
The error was "error: macro "INIT_WORK" passed 3 arguments, but takes just 2"
So I found one solution and use the below line
INIT_WORK(&task, got_char);
It's working fine but the output I am getting is null. I am expecting the key number from the keyboard.
Any body have any idea ?
If it is not clear please let me know I will try to interpret more.
Thanks
Add a structure like follows,
struct getchar_info {
/* Other info ... */
struct work_struct work;
unsigned int scancode;
/* Other info ... */
};
static struct getchar_info gci; /* Statically declare or use kmalloc() */
Change got_char() to,
static void got_char(struct work_struct *work)
{
struct getchar_info *info = container_of(work, struct getchar_info, work);
info->scancode = my_val;
/* ... */
Initialize it like INIT_WORK(&gci.work, got_char);
This is a common Linux kernel paradigm or design pattern. The work queue code needs to manage this structure pointer so it is easy to provide to your got_char routine. Your driver must allocate it as part of a larger structure (it is inheritence in OO terms; it looks like composition as 'C' only supports that). The container_of is like a C++ dynamic_cast<> (with single inheritance in case any C++ gurus are looking). It lets you get the composed structure from the sub-structure.

Linux Kernel - Inner Crypto API

Since I will use the Linux's built-in crypto API for different purposes, I've been reading the sources carefully.
While attempting to understand what's going on, I have been struck by the instance handling part of the code.
The code is C, nevertheless this part is clearly object-oriented. Thus, when a user needs to perform some encryption, it will ask for the allocation of a transform instance which will involve the use of a particular algorithm in a particular encryption mode. The pair (algorithm, mode) will be handled this way in the crypto API :
The "pure" algorithm is stored in a struct crypto_alg structure.
The mode is defined through a struct crypto_template which says how to initialize a specific struct crypto_instance
Here are the definitions of the structures crypto_instance and crypto_spawn
struct crypto_instance {
struct crypto_alg alg;
/*
* The alg struct will be filled according to the template 'alloc' method
*/
struct crypto_template *tmpl;
struct hlist_node list;
void *__ctx[] CRYPTO_MINALIGN_ATTR;
};
struct crypto_spawn {
struct list_head list; // Embedded list_head to list the spawns
struct crypto_alg *alg; // Ptr to the underlying algorithm
struct crypto_instance *inst;
const struct crypto_type *frontend;
u32 mask;
}
Then, to me it looks like there is a kind of hierarchy : the crypto_spawn is here to manage the combination of an encryption mode defined by a crypto_instance and a pure encryption algorithm defined by a crypto_alg. In terms of model object, we can see that crypto_instance inherits crypto_alg and it is totally reasonable to consider "cascading" templates over a given algorithm.
The thing I don't understand is why the crypto_spawn and the crypto_instance structures are not merged together. This question has even more struck me when I met the instance allocation code :
struct crypto_instance *crypto_alloc_instance(const char *name,
struct crypto_alg *alg)
{
struct crypto_instance *inst;
struct crypto_spawn *spawn;
int err;
inst = crypto_alloc_instance2(name, alg, 0);
if (IS_ERR(inst))
goto out;
spawn = crypto_instance_ctx(inst);
/*
* This line expands to :
* spawn = inst->__ctx;
*/
err = crypto_init_spawn(spawn, alg, inst,
CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_ASYNC);
if (err)
goto err_free_inst;
return inst;
err_free_inst:
kfree(inst);
inst = ERR_PTR(err);
out:
return inst;
}
The crypto_alloc_instance2 just allocates the physical memory to hold the structure and fills the inst->alg structure's name fields :
void *crypto_alloc_instance2(const char *name, struct crypto_alg *alg,
unsigned int head)
{
struct crypto_instance *inst;
char *p;
int err;
p = kzalloc(head + sizeof(*inst) + sizeof(struct crypto_spawn),
GFP_KERNEL);
if (!p)
return ERR_PTR(-ENOMEM);
inst = (void *)(p + head);
/* Names editing + error checking ... */
return p;
}
As you can see, a spawn is "physically" bound to an instance, so why are they defined separately. I find it very troubling when then trying to understand how the whole thing is mixed and handled.
At the moment, the only reason that came to my mind is that it allows the API to opacify the underlying algorithm from the crypto_instance object. But since the last bytes of the structure will easily give the spawn through the spawn = inst->__ctx instruction, it is not very very opaque.
As a recall after this bunch of code and comments, the question is :
What reasons lead the developers to make this "separation" between the instance and the spawn structure ?
Thanks in advance for any enlightenment !
Note : I added the tag cryptography because I thought that developers interested in this tag have probably already taken a look into the Linux Kernel crypto part.

Resources