Note that there are some explanatory texts on larger screens.

plurals
  1. POStatic allocation of opaque data types
    primarykey
    data
    text
    <p>Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:</p> <pre><code>// In file module.h typedef struct handle_t handle_t; handle_t *create_handle(); void operation_on_handle(handle_t *handle, int an_argument); void another_operation_on_handle(handle_t *handle, char etcetera); void close_handle(handle_t *handle); // In file module.c struct handle_t { int foo; void *something; int another_implementation_detail; }; handle_t *create_handle() { handle_t *handle = malloc(sizeof(struct handle_t)); // other initialization return handle; } </code></pre> <p>There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:</p> <pre><code>void create_handle(handle_t *handle); </code></pre> <p>And then the caller could create the handle this way:</p> <pre><code>// In file caller.c void i_am_the_caller() { handle_t a_handle; // Allocate a handle on the stack instead of malloc() create_handle(&amp;a_handle); // ... a_handle is ready to go! } </code></pre> <p>But unfortunately this code is obviously invalid, the size of handle_t isn't known!</p> <p>I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload